logger.rs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. use log::Level;
  2. use std::io::Write;
  3. use crate::Cli;
  4. /// Simple logger implementation for RustSBI that supports colored output.
  5. pub struct Logger;
  6. impl Logger {
  7. /// Initialize the logger with log level from RUST_LOG env var or default to Info.
  8. pub fn init(cli: &Cli) -> Result<(), log::SetLoggerError> {
  9. // Set max log level from parmas env var if present, otherwise use Info
  10. log::set_max_level(cli.verbose.log_level_filter());
  11. log::set_logger(&Logger)
  12. }
  13. }
  14. impl log::Log for Logger {
  15. // Always enable logging for all log levels
  16. #[inline]
  17. fn enabled(&self, _metadata: &log::Metadata) -> bool {
  18. true
  19. }
  20. // Log messages with color-coded levels
  21. #[inline]
  22. fn log(&self, record: &log::Record) {
  23. // ANSI color codes for different log levels
  24. const ERROR_COLOR: u8 = 31; // Red
  25. const WARN_COLOR: u8 = 93; // Bright yellow
  26. const INFO_COLOR: u8 = 32; // Green
  27. const DEBUG_COLOR: u8 = 36; // Cyan
  28. const TRACE_COLOR: u8 = 90; // Bright black
  29. let color_code = match record.level() {
  30. Level::Error => ERROR_COLOR,
  31. Level::Warn => WARN_COLOR,
  32. Level::Info => INFO_COLOR,
  33. Level::Debug => DEBUG_COLOR,
  34. Level::Trace => TRACE_COLOR,
  35. };
  36. eprintln!(
  37. "\x1b[1;37m[RustSBI-xtask] \x1b[1;{color_code}m{:^5}\x1b[0m - {}",
  38. record.level(),
  39. record.args(),
  40. );
  41. }
  42. // No-op flush since we use println! which is already line-buffered
  43. #[inline]
  44. fn flush(&self) {
  45. std::io::stderr().flush().expect("Unable to flush stderr");
  46. }
  47. }