logging.rs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright (c) 2006-2024, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author notes
  8. * 2025-10-20 foxglove micro rust log component
  9. */
  10. /* Basic logging primitives and console output helpers */
  11. use alloc::string::String;
  12. use rt_rust::println;
  13. #[repr(usize)]
  14. #[derive(Debug, Copy, Clone, PartialEq, Eq)]
  15. pub enum Level {
  16. Error = 1,
  17. Warn = 2,
  18. Info = 3,
  19. Debug = 4,
  20. Trace = 5,
  21. }
  22. /* Top-level logging macro */
  23. #[macro_export]
  24. macro_rules! log {
  25. ($level:expr, $($arg:tt)*) => ({
  26. $crate::logging::_log($level, format_args!($($arg)*));
  27. });
  28. }
  29. /* Error-level logging */
  30. #[macro_export]
  31. macro_rules! error {
  32. ($($arg:tt)*) => ({
  33. $crate::logging::_log($crate::logging::Level::Error, format_args!($($arg)*));
  34. });
  35. }
  36. /* Warning-level logging */
  37. #[macro_export]
  38. macro_rules! warn {
  39. ($($arg:tt)*) => ({
  40. $crate::logging::_log($crate::logging::Level::Warn, format_args!($($arg)*));
  41. });
  42. }
  43. /* Info-level logging */
  44. #[macro_export]
  45. macro_rules! info {
  46. ($($arg:tt)*) => ({
  47. $crate::logging::_log($crate::logging::Level::Info, format_args!($($arg)*));
  48. });
  49. }
  50. /* Debug-level logging */
  51. #[macro_export]
  52. macro_rules! debug {
  53. ($($arg:tt)*) => ({
  54. $crate::logging::_log($crate::logging::Level::Debug, format_args!($($arg)*));
  55. });
  56. }
  57. /* Trace-level logging */
  58. #[macro_export]
  59. macro_rules! trace {
  60. ($($arg:tt)*) => ({
  61. $crate::logging::_log($crate::logging::Level::Trace, format_args!($($arg)*));
  62. });
  63. }
  64. /* Internal logging handler: formats message and prints with color */
  65. pub fn _log(level: Level, args: core::fmt::Arguments) {
  66. use core::fmt::Write;
  67. use rt_rust::time;
  68. let mut s = String::new();
  69. write!(&mut s, "[{:?}][{:?}]", level, time::get_time()).unwrap();
  70. write!(&mut s, "{}", args).unwrap();
  71. match level {
  72. Level::Error => {
  73. println!("\x1b[1;31m{}\x1b[0m", s);
  74. }
  75. Level::Warn => {
  76. println!("\x1b[1;33m{}\x1b[0m", s);
  77. }
  78. Level::Info => {
  79. println!("\x1b[1;32m{}\x1b[0m", s);
  80. }
  81. Level::Debug => {
  82. println!("\x1b[1;34m{}\x1b[0m", s);
  83. }
  84. Level::Trace => {
  85. println!("\x1b[1;30m{}\x1b[0m", s);
  86. }
  87. }
  88. }