printk.rs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. use core::fmt::{self, Write};
  2. use alloc::string::ToString;
  3. use log::{info, Level, Log};
  4. use super::lib_ui::textui::{textui_putstr, FontColor};
  5. use crate::{
  6. driver::tty::{tty_driver::TtyOperation, virtual_terminal::vc_manager},
  7. filesystem::procfs::{
  8. kmsg::KMSG,
  9. log::{LogLevel, LogMessage},
  10. },
  11. time::PosixTimeSpec,
  12. };
  13. #[macro_export]
  14. macro_rules! print {
  15. ($($arg:tt)*) => ($crate::libs::printk::__printk(format_args!($($arg)*)));
  16. }
  17. #[macro_export]
  18. macro_rules! println {
  19. () => {
  20. $crate::print!("\n");
  21. };
  22. ($($arg:tt)*) => ($crate::print!("{}\n", format_args!($($arg)*)));
  23. }
  24. pub struct PrintkWriter;
  25. impl PrintkWriter {
  26. #[inline]
  27. pub fn __write_fmt(&mut self, args: fmt::Arguments) {
  28. self.write_fmt(args).ok();
  29. }
  30. /// 并输出白底黑字
  31. /// @param str: 要写入的字符
  32. pub fn __write_string(&mut self, s: &str) {
  33. if let Some(current_vc) = vc_manager().current_vc() {
  34. // tty已经初始化了之后才输出到屏幕
  35. let port = current_vc.port();
  36. let tty = port.port_data().internal_tty();
  37. if let Some(tty) = tty {
  38. let _ = tty.write(tty.core(), s.as_bytes(), s.len());
  39. } else {
  40. let _ = textui_putstr(s, FontColor::WHITE, FontColor::BLACK);
  41. }
  42. } else {
  43. let _ = textui_putstr(s, FontColor::WHITE, FontColor::BLACK);
  44. }
  45. }
  46. }
  47. /// 为Printk Writer实现core::fmt::Write, 使得能够借助Rust自带的格式化组件,格式化字符并输出
  48. impl fmt::Write for PrintkWriter {
  49. fn write_str(&mut self, s: &str) -> fmt::Result {
  50. self.__write_string(s);
  51. Ok(())
  52. }
  53. }
  54. #[doc(hidden)]
  55. pub fn __printk(args: fmt::Arguments) {
  56. PrintkWriter.write_fmt(args).unwrap();
  57. }
  58. pub struct Logger;
  59. impl Logger {
  60. pub fn log(&self, log_level: usize, message: fmt::Arguments) {
  61. if unsafe { KMSG.is_some() } {
  62. let timestamp: PosixTimeSpec = PosixTimeSpec::now_cpu_time();
  63. let log_level = LogLevel::from(log_level);
  64. let log_message = LogMessage::new(timestamp, log_level, message.to_string());
  65. unsafe { KMSG.as_ref().unwrap().lock_irqsave().push(log_message) };
  66. }
  67. }
  68. }
  69. /// 内核自定义日志器
  70. ///
  71. /// todo: https://github.com/DragonOS-Community/DragonOS/issues/762
  72. struct KernelLogger;
  73. impl Log for KernelLogger {
  74. fn enabled(&self, _metadata: &log::Metadata) -> bool {
  75. // 这里可以自定义日志过滤规则
  76. true
  77. }
  78. fn log(&self, record: &log::Record) {
  79. if self.enabled(record.metadata()) {
  80. // todo: 接入kmsg
  81. Self::kernel_log(record);
  82. Self::iodisplay(record)
  83. }
  84. }
  85. fn flush(&self) {
  86. // 如果需要的话,可以在这里实现缓冲区刷新逻辑
  87. }
  88. }
  89. impl KernelLogger {
  90. fn iodisplay(record: &log::Record) {
  91. match record.level() {
  92. Level::Debug | Level::Info | Level::Trace => {
  93. write!(PrintkWriter, "[ {} ] ", record.level(),)
  94. }
  95. Level::Error => {
  96. write!(PrintkWriter, "\x1B[41m[ ERROR ] \x1B[0m",)
  97. }
  98. Level::Warn => {
  99. write!(PrintkWriter, "\x1B[1;33m[ WARN ] \x1B[0m",)
  100. }
  101. }
  102. .unwrap();
  103. writeln!(
  104. PrintkWriter,
  105. "({}:{})\t {}",
  106. record.file().unwrap_or(""),
  107. record.line().unwrap_or(0),
  108. record.args()
  109. )
  110. .unwrap();
  111. }
  112. fn kernel_log(record: &log::Record) {
  113. match record.level() {
  114. Level::Debug => Logger.log(
  115. 7,
  116. format_args!(
  117. "({}:{})\t {}\n",
  118. record.file().unwrap_or(""),
  119. record.line().unwrap_or(0),
  120. record.args()
  121. ),
  122. ),
  123. Level::Error => Logger.log(
  124. 3,
  125. format_args!(
  126. "({}:{})\t {}\n",
  127. record.file().unwrap_or(""),
  128. record.line().unwrap_or(0),
  129. record.args()
  130. ),
  131. ),
  132. Level::Info => Logger.log(
  133. 6,
  134. format_args!(
  135. "({}:{})\t {}\n",
  136. record.file().unwrap_or(""),
  137. record.line().unwrap_or(0),
  138. record.args()
  139. ),
  140. ),
  141. Level::Warn => Logger.log(
  142. 4,
  143. format_args!(
  144. "({}:{})\t {}\n",
  145. record.file().unwrap_or(""),
  146. record.line().unwrap_or(0),
  147. record.args()
  148. ),
  149. ),
  150. Level::Trace => {
  151. todo!()
  152. }
  153. }
  154. }
  155. }
  156. pub fn early_init_logging() {
  157. log::set_logger(&KernelLogger).unwrap();
  158. log::set_max_level(log::LevelFilter::Debug);
  159. info!("Logging initialized");
  160. }