openethereum/util/src/log.rs

92 lines
2.1 KiB
Rust
Raw Normal View History

2016-02-05 13:40:41 +01:00
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
2016-01-29 15:01:39 +01:00
//! Common log helper functions
use std::env;
use rlog::{LogLevelFilter};
use env_logger::LogBuilder;
2016-04-19 09:58:26 +02:00
use std::sync::{RwLock, RwLockReadGuard};
2016-04-19 19:08:13 +02:00
use arrayvec::ArrayVec;
2016-01-29 15:01:39 +01:00
lazy_static! {
static ref LOG_DUMMY: bool = {
let mut builder = LogBuilder::new();
builder.filter(None, LogLevelFilter::Info);
if let Ok(log) = env::var("RUST_LOG") {
builder.parse(&log);
}
if let Ok(_) = builder.init() {
println!("logger initialized");
}
true
};
}
/// Intialize log with default settings
pub fn init_log() {
let _ = *LOG_DUMMY;
}
2016-04-19 09:58:26 +02:00
2016-04-19 19:08:13 +02:00
const LOG_SIZE : usize = 128;
2016-04-19 09:58:26 +02:00
2016-04-19 19:08:13 +02:00
/// Logger implementation that keeps up to `LOG_SIZE` log elements.
2016-04-19 09:58:26 +02:00
pub struct RotatingLogger {
2016-04-19 19:08:13 +02:00
/// Defined logger levels
2016-04-19 09:58:26 +02:00
levels: String,
2016-04-19 19:08:13 +02:00
/// Logs array. Latest log is always at index 0
logs: RwLock<ArrayVec<[String; LOG_SIZE]>>,
2016-04-19 09:58:26 +02:00
}
impl RotatingLogger {
2016-04-19 19:08:13 +02:00
/// Creates new `RotatingLogger` with given levels.
/// It does not enforce levels - it's just read only.
2016-04-19 09:58:26 +02:00
pub fn new(levels: String) -> Self {
RotatingLogger {
levels: levels,
2016-04-19 19:08:13 +02:00
logs: RwLock::new(ArrayVec::<[_; LOG_SIZE]>::new()),
2016-04-19 09:58:26 +02:00
}
}
2016-04-19 19:08:13 +02:00
/// Append new log entry
2016-04-19 09:58:26 +02:00
pub fn append(&self, log: String) {
2016-04-19 19:08:13 +02:00
self.logs.write().unwrap().insert(0, log);
2016-04-19 09:58:26 +02:00
}
2016-04-19 19:08:13 +02:00
/// Return levels
2016-04-19 09:58:26 +02:00
pub fn levels(&self) -> &str {
&self.levels
}
2016-04-19 19:08:13 +02:00
/// Return logs
pub fn logs(&self) -> RwLockReadGuard<ArrayVec<[String; LOG_SIZE]>> {
2016-04-19 09:58:26 +02:00
self.logs.read().unwrap()
}
}
#[cfg(test)]
mod test {
#[test]
fn should_have_some_tests() {
assert_eq!(true, false);
}
}