logger.rs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. use log::Record;
  2. use std::cell::Cell;
  3. use std::future::Future;
  4. use std::pin::Pin;
  5. use uuid::Uuid;
  6. thread_local! {
  7. static REQUEST_ID: Cell<Option<Uuid>> = Cell::new(None);
  8. }
  9. fn format_record_to_buf(
  10. f: &mut env_logger::fmt::Formatter,
  11. record: &Record,
  12. ) -> std::io::Result<()> {
  13. use std::io::Write;
  14. let rid = REQUEST_ID.with(|rid| {
  15. if let Some(uuid) = rid.get() {
  16. format!(" request_id={}", uuid)
  17. } else {
  18. String::from("")
  19. }
  20. });
  21. writeln!(
  22. f,
  23. "[{time} {level:<5} {module_path} {file}:{line}]{request_id} {record}",
  24. time = f.timestamp_millis(),
  25. request_id = rid,
  26. level = record.level(),
  27. module_path = record.module_path().unwrap_or(""),
  28. file = record.file().unwrap_or("???"),
  29. line = record.line().map(|l| l as i64).unwrap_or(-1),
  30. record = record.args(),
  31. )
  32. }
  33. pub fn init() {
  34. eprintln!("setting logger");
  35. log::set_boxed_logger(Box::new(
  36. env_logger::Builder::from_default_env()
  37. .format(format_record_to_buf)
  38. .build(),
  39. ))
  40. .unwrap();
  41. log::set_max_level(log::LevelFilter::Trace);
  42. log::trace!("initialized logging infra");
  43. }
  44. pub struct LogFuture<F> {
  45. uuid: Uuid,
  46. future: F,
  47. }
  48. impl<F: Future> Future for LogFuture<F> {
  49. type Output = F::Output;
  50. fn poll(
  51. self: Pin<&mut Self>,
  52. cx: &mut std::task::Context<'_>,
  53. ) -> std::task::Poll<Self::Output> {
  54. unsafe {
  55. let self_ = self.get_unchecked_mut();
  56. REQUEST_ID.with(|thread| {
  57. let uuid = self_.uuid;
  58. thread.set(Some(uuid));
  59. let fut = Pin::new_unchecked(&mut self_.future);
  60. let ret = fut.poll(cx);
  61. thread.set(None);
  62. ret
  63. })
  64. }
  65. }
  66. }
  67. impl<F> LogFuture<F> {
  68. pub fn new(uuid: Uuid, future: F) -> Self {
  69. Self { uuid, future }
  70. }
  71. }