/src/logger.rs

https://github.com/gnzlbg/cargo-asm · Rust · 71 lines · 47 code · 7 blank · 17 comment · 2 complexity · 26a2304424db7d642a32c0bdfed7908e MD5 · raw file

  1. // This logger has been adapted from ripgrep:
  2. // https://github.com/BurntSushi/ripgrep
  3. //
  4. // This module defines a super simple logger that works with the `log` crate.
  5. // We don't need anything fancy; just basic log levels and the ability to
  6. // print to stderr. We therefore avoid bringing in extra dependencies just
  7. // for this functionality.
  8. use log::{self, Log};
  9. /// The simplest possible logger that logs to stderr.
  10. ///
  11. /// This logger does no filtering. Instead, it relies on the `log` crates
  12. /// filtering via its global `max_level` setting.
  13. #[derive(Debug)]
  14. pub struct Logger(());
  15. const LOGGER: &Logger = &Logger(());
  16. impl Logger {
  17. /// Create a new logger that logs to stderr and initialize it as the
  18. /// global logger. If there was a problem setting the logger, then an
  19. /// error is returned.
  20. pub fn init() -> Result<(), log::SetLoggerError> {
  21. log::set_logger(LOGGER)
  22. }
  23. }
  24. impl Log for Logger {
  25. fn enabled(&self, _: &log::Metadata) -> bool {
  26. // We set the log level via log::set_max_level, so we don't need to
  27. // implement filtering here.
  28. true
  29. }
  30. fn log(&self, record: &log::Record) {
  31. match (record.file(), record.line()) {
  32. (Some(file), Some(line)) => {
  33. eprintln!(
  34. "[{}][{}][{}:{}]: {}",
  35. record.level(),
  36. record.target(),
  37. file,
  38. line,
  39. record.args()
  40. );
  41. }
  42. (Some(file), None) => {
  43. eprintln!(
  44. "[{}][{}][{}]: {}",
  45. record.level(),
  46. record.target(),
  47. file,
  48. record.args()
  49. );
  50. }
  51. _ => {
  52. eprintln!(
  53. "[{}][{}]: {}",
  54. record.level(),
  55. record.target(),
  56. record.args()
  57. );
  58. }
  59. }
  60. }
  61. fn flush(&self) {
  62. // We use eprintln! which is flushed on every call.
  63. }
  64. }