1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
//! A consumer for the log crate
//!
//! The crate implements a logger that allows module-wise configuration of logging through
//! configuration files or an API.
//!
//! Features
//! * Log output can be written to stdout, stderr, to file or to a memory buffer.
//! * Log output can be colored.
//! * Features can be set using a configuration file or the API
//!
//! The configuration file can be enabled by setting the environment variable ```LOG_CONFIG``` to the
//! path of the file. The configuration is specified in YAML format and allows to set the following
//! values. All values are optional.
//!
//! * default_level: The default log level, one of trace, debug, info, warn, error, defaults to info
//! * mod_level: A list of module name and log level pairs
//! * log_dest: One of stdout, stderr, stream, buffer, streamstdout, streamstderr, bufferstdout, bufferstderr.
//! * log_stream: The log file name for stream variants of log_dest
//! * color: one of ```true``` or ```false```
//! * brief_info: one of ```true``` or ```false```
//!
//! Sample:
//! ```yaml
//! log_level: warn
//! log_dest: streamstderr
//! log_stream: debug.log
//! color: true
//! brief_info: true
//! mod_level:
//! 'test_mod': debug
//! 'test_mod::test_test': trace
//! ```
//!
use chrono::Local;
use colored::*;
use log::{Log, Metadata, Record};
use regex::Regex;
use std::env;
use std::fs::File;
#[cfg(feature = "config")]
use std::fs::OpenOptions;
use std::io::{stderr, stdout, BufWriter, Write};
use std::mem;
use std::sync::{Arc, Mutex, Once};
//, BufWriter};
mod error;
use error::{Error, ErrorKind, Result};
use std::path::Path;
#[cfg(feature = "config")]
pub mod config;
#[cfg(feature = "config")]
pub use config::LogConfig;
#[cfg(feature = "config")]
pub use config::LogConfigBuilder;
mod logger_params;
pub use logger_params::LogDestination;
use logger_params::LoggerParams;
pub(crate) const DEFAULT_LOG_LEVEL: Level = Level::Info;
// cannot be STREAM !!
pub(crate) const DEFAULT_LOG_DEST: LogDestination = LogDestination::Stderr;
pub const NO_STREAM: Option<Box<dyn 'static + Write + Send>> = None;
use crate::error::ToError;
pub use log::Level;
// TODO: implement size limit for memory buffer
// TODO: Drop initialise functions and rather use a set_config function that can repeatedly reset the configuration
/// The Logger struct holds a singleton containing all relevant information.
///
/// struct Logger has a private constructor. It is used via its static interface which will
/// instantiate a Logger or use an existing one.
#[derive(Clone)]
pub struct Logger {
inner: Arc<Mutex<LoggerParams>>,
module_re: Regex,
exe_name: Option<String>,
}
impl Logger {
/// Create a new Logger or retrieve the existing one.\
/// The function is private, Logger is meant to be used via its static interface
/// Any of the static functions will initialise a Logger instance
fn new() -> Logger {
static mut LOGGER: *const Logger = 0 as *const Logger;
static ONCE: Once = Once::new();
// dbg!("Logger::new: entered");
let exe_name = match env::current_exe() {
Ok(exe_name) => match exe_name.file_name() {
Some(exe_name) => exe_name
.to_str()
.map(|name| name.to_owned().replace('-', "_")),
None => None,
},
Err(_why) => None,
};
let logger = unsafe {
ONCE.call_once(|| {
let singleton = Logger {
module_re: Regex::new(r#"^([^:]+)::(.*)$"#).unwrap(),
inner: Arc::new(Mutex::new(LoggerParams::new(DEFAULT_LOG_LEVEL))),
exe_name,
};
// Put it in the heap so it can outlive this call
LOGGER = mem::transmute(Box::new(singleton));
});
(*LOGGER).clone()
};
// is initialised tests and sets the flag
if !logger.inner.lock().unwrap().initialised() {
// looks like we only just created it
// look for LOG_CONFIG in ENV
#[cfg(feature = "config")]
if let Ok(config_path) = env::var("LOG_CONFIG") {
// eprintln!("LOG_CONFIG={}", config_path);
match LogConfigBuilder::from_file(&config_path) {
Ok(ref log_config) => match logger.int_set_log_config(log_config.build()) {
Ok(_res) => (),
Err(why) => {
eprintln!(
"Failed to apply log config from file: '{}', error: {:?}",
config_path, why
);
}
},
Err(why) => {
eprintln!(
"Failed to read log config from file: '{}', error: {:?}",
config_path, why
);
}
}
}
// potential race condition here regarding max_level
match log::set_boxed_logger(Box::new(logger.clone())) {
Ok(_dummy) => (),
Err(why) => {
dbg!(why);
}
}
log::set_max_level(logger.inner.lock().unwrap().max_level().to_level_filter());
}
// dbg!("Logger::new: done");
// Now we give out a copy of the data that is safe to use concurrently.
logger
}
/// Flush the contents of log buffers
pub fn flush() {
Logger::new().flush();
}
/// create a default logger
pub fn create() {
let _logger = Logger::new();
}
/// Initialise a Logger with the given default log_level or modify the default log level of the
/// existing logger
pub fn set_default_level(log_level: Level) {
let logger = Logger::new();
let mut guarded_params = logger.inner.lock().unwrap();
let last_max_level = *guarded_params.max_level();
let max_level = guarded_params.set_default_level(log_level);
if last_max_level != max_level {
log::set_max_level(max_level.to_level_filter());
}
}
/// Retrieve the default level of the logger
pub fn get_default_level(&self) -> Level {
let guarded_params = self.inner.lock().unwrap();
guarded_params.get_default_level()
}
/// Modify the log level for a module
pub fn set_mod_level(module: &str, log_level: Level) {
let logger = Logger::new();
let mut guarded_params = logger.inner.lock().unwrap();
let last_max_level = *guarded_params.max_level();
let max_level = guarded_params.set_mod_level(module, log_level);
if last_max_level != *max_level {
log::set_max_level(max_level.to_level_filter());
}
}
/// Retrieve the current log buffer, if available
pub fn get_buffer() -> Option<Vec<u8>> {
let logger = Logger::new();
let mut guarded_params = logger.inner.lock().unwrap();
guarded_params.retrieve_log_buffer()
}
/// Set the log destination
pub fn set_log_dest<S: 'static + Write + Send>(
dest: &LogDestination,
stream: Option<S>,
) -> Result<()> {
let logger = Logger::new();
logger.flush();
let mut guarded_params = logger.inner.lock().unwrap();
guarded_params.set_log_dest(dest, stream)
}
/// Set log destination and log file.
pub fn set_log_file(log_dest: &LogDestination, log_file: &Path, buffered: bool) -> Result<()> {
let dest = if log_dest.is_stdout() {
LogDestination::StreamStdout
} else if log_dest.is_stderr() {
LogDestination::StreamStderr
} else {
LogDestination::Stream
};
let mut stream: Box<dyn Write + Send> = if buffered {
Box::new(BufWriter::new(
File::create(log_file).upstream_with_context(&format!(
"Failed to create file: '{}'",
log_file.display()
))?,
))
} else {
Box::new(File::create(log_file).upstream_with_context(&format!(
"Failed to create file: '{}'",
log_file.display()
))?)
};
let logger = Logger::new();
logger.flush();
let mut guarded_params = logger.inner.lock().unwrap();
let buffer = guarded_params.retrieve_log_buffer();
if let Some(buffer) = buffer {
stream
.write_all(buffer.as_slice())
.upstream_with_context(&format!(
"Failed to write buffers to file: '{}'",
log_file.display()
))?;
stream.flush().upstream_with_context(&format!(
"Failed to flush buffers to file: '{}'",
log_file.display()
))?;
}
guarded_params.set_log_dest(&dest, Some(stream))
}
/// Retrieve the current log destination
pub fn get_log_dest() -> LogDestination {
let logger = Logger::new();
let guarded_params = logger.inner.lock().unwrap();
guarded_params.get_log_dest().clone()
}
/// Set the log configuration.
#[cfg(feature = "config")]
pub fn set_log_config(log_config: &LogConfig) -> Result<()> {
Logger::new().int_set_log_config(log_config)
}
/// Enable / disable colored output
pub fn set_color(color: bool) {
let logger = Logger::new();
let mut guarded_params = logger.inner.lock().unwrap();
guarded_params.set_color(color)
}
/// Enable / disable timestamp in messages
pub fn set_timestamp(val: bool) {
let logger = Logger::new();
let mut guarded_params = logger.inner.lock().unwrap();
guarded_params.set_timestamp(val)
}
/// Enable / disable timestamp in messages
pub fn set_millis(val: bool) {
let logger = Logger::new();
let mut guarded_params = logger.inner.lock().unwrap();
guarded_params.set_millis(val)
}
/// Enable / disable brief info messages
pub fn set_brief_info(val: bool) {
let logger = Logger::new();
let mut guarded_params = logger.inner.lock().unwrap();
guarded_params.set_brief_info(val)
}
#[cfg(feature = "config")]
fn int_set_log_config(&self, log_config: &LogConfig) -> Result<()> {
let mut guarded_params = self.inner.lock().unwrap();
let last_max_level = *guarded_params.max_level();
guarded_params.set_default_level(log_config.get_default_level());
let max_level = guarded_params.set_mod_config(log_config.get_mod_level());
if max_level != &last_max_level {
log::set_max_level(max_level.to_level_filter());
}
let log_dest = guarded_params.get_log_dest();
let cfg_log_dest = log_config.get_log_dest();
let stream_log = cfg_log_dest.is_stream_dest();
if cfg_log_dest != log_dest || stream_log {
if stream_log {
if let Some(log_stream) = log_config.get_log_stream() {
guarded_params.set_log_dest(
cfg_log_dest,
Some(
OpenOptions::new()
.append(true)
.create(true)
.open(log_stream)
.upstream_with_context(&format!(
"Failed to open log file: '{}'",
log_stream.display()
))?,
),
)?;
} else {
return Err(Error::with_context(
ErrorKind::InvParam,
&format!(
"Missing parameter log_stream for destination {:?}",
cfg_log_dest
),
));
}
} else {
guarded_params.set_log_dest(cfg_log_dest, NO_STREAM)?;
}
}
guarded_params.set_color(log_config.is_color());
guarded_params.set_brief_info(log_config.is_brief_info());
Ok(())
}
}
impl Log for Logger {
fn enabled(&self, _metadata: &Metadata) -> bool {
true
}
fn log(&self, record: &Record) {
let (mod_name, mod_tag) = if let Some(mod_path) = record.module_path() {
if let Some(ref exe_name) = self.exe_name {
if let Some(ref captures) = self.module_re.captures(mod_path) {
if captures.get(1).unwrap().as_str() == exe_name {
(
mod_path.to_owned(),
captures.get(2).unwrap().as_str().to_owned(),
)
} else {
(mod_path.to_owned(), mod_path.to_owned())
}
} else if mod_path == exe_name {
(mod_path.to_owned(), String::from("main"))
} else {
(mod_path.to_owned(), mod_path.to_owned())
}
} else {
(mod_path.to_owned(), mod_path.to_owned())
}
} else {
(String::from("undefined"), String::from("undefined"))
};
let curr_level = record.metadata().level();
let mut guarded_params = self.inner.lock().unwrap();
let mut level = guarded_params.get_default_level();
if let Some(mod_level) = guarded_params.get_mod_level(&mod_tag) {
level = mod_level;
}
if curr_level <= level {
let timestamp = if guarded_params.timestamp() {
let now = Local::now();
if guarded_params.millis() {
let ts_millis = now.timestamp_millis() % 1000;
format!("{}.{:03} ", now.format("%Y-%m-%d %H:%M:%S"), ts_millis)
} else {
format!("{} ", now.format("%Y-%m-%d %H:%M:%S"))
}
} else {
"".to_owned()
};
let mut output = if guarded_params.brief_info() && (curr_level == Level::Info) {
format!(
"{}{:<5} {}\n",
timestamp,
record.level().to_string(),
record.args()
)
} else {
format!(
"{}{:<5} [{}] {}\n",
timestamp,
record.level().to_string(),
&mod_name,
record.args()
)
};
if guarded_params.color() {
output = match curr_level {
Level::Error => format!("{}", output.red()),
Level::Warn => format!("{}", output.yellow()),
Level::Info => format!("{}", output.green()),
Level::Debug => format!("{}", output.cyan()),
Level::Trace => format!("{}", output.blue()),
};
}
let _res = match guarded_params.get_log_dest() {
LogDestination::Stderr => stderr().write(output.as_bytes()),
LogDestination::Stdout => stdout().write(output.as_bytes()),
LogDestination::Stream => {
if let Some(ref mut stream) = guarded_params.log_stream() {
stream.write(output.as_bytes())
} else {
stderr().write(output.as_bytes())
}
}
LogDestination::StreamStdout => {
if let Some(ref mut stream) = guarded_params.log_stream() {
let _wres = stream.write(output.as_bytes());
}
stdout().write(output.as_bytes())
}
LogDestination::StreamStderr => {
if let Some(ref mut stream) = guarded_params.log_stream() {
let _wres = stream.write(output.as_bytes());
}
stderr().write(output.as_bytes())
}
LogDestination::Buffer => {
if let Some(ref mut buffer) = guarded_params.log_buffer() {
buffer.write(output.as_bytes())
} else {
stderr().write(output.as_bytes())
}
}
LogDestination::BufferStdout => {
if let Some(ref mut buffer) = guarded_params.log_buffer() {
let _wres = buffer.write(output.as_bytes());
}
stdout().write(output.as_bytes())
}
LogDestination::BufferStderr => {
if let Some(ref mut buffer) = guarded_params.log_buffer() {
let _wres = buffer.write(output.as_bytes());
}
stderr().write(output.as_bytes())
}
};
}
}
fn flush(&self) {
let mut guarded_params = self.inner.lock().unwrap();
guarded_params.flush();
}
}
/*
#[cfg(test)]
mod test {
use log::{info};
use crate::{Logger, LogDestination};
#[test]
fn log_to_mem() {
Logger::initialise(Some("debug")).unwrap();
let buffer: Vec<u8> = vec![];
Logger::set_log_dest(&LogDestination::STREAM, Some(buffer)).unwrap();
info!("logging to memory buffer");
assert!(!buffer.is_empty());
}
}
*/