rust 日志记载与跟踪

打印 上一主题 下一主题

主题 529|帖子 529|积分 1587

日志

Cargo.toml

  1. [dependencies]
  2. warp = "0.3.7"
  3. tokio = {version = "1.39.3", features = ["full"]}
  4. serde = { version = "1.0.208", features = ["derive"] }
  5. serde_json = "1.0.125"
  6. #log = "0.4"
  7. #env_logger = "0.11"
  8. #log4rs = "1.3.0"
  9. tracing = {version = "0.1.40", features = ["log"]}
  10. tracing-subscriber = {version = "0.3.18", features = ["env-filter"]}
  11. uuid = {version = "0.8", features = ["v4"]}
复制代码
日志记载

env_logger

  1. log = "0.4"
  2. env_logger = "0.11"
  3. #log4rs = "1.3.0"
复制代码
  1. $ RUST_LOG=info cargo run -p wrap_demo01 --bin wrap_demo01
  2. $ RUST_LOG=debug cargo run -p wrap_demo01 --bin wrap_demo01
复制代码
log4rs

  1. log = "0.4"
  2. #env_logger = "0.11"
  3. log4rs = "1.3.0"
复制代码
记载 HTTP 请求



  • 输出到控制台
  • 输出到文件
log4rs.yaml 设置
  1. refresh_rate: 30 seconds
  2. appenders:
  3.    stdout:
  4.      kind: console
  5.      encoder:
  6.        kind: json
  7.    file:
  8.      kind: file
  9.      path: "stderr.log"
  10.      encoder:
  11.        kind : json
  12.        #pattern: "{d} - {m}{n}"
  13. root:
  14.   level: info
  15.   appenders:
  16.     - stdout
  17.     - file
复制代码
  1. log4rs::init_file("log4rs.yaml", Default::default()).unwrap();
  2. let log = warp::log::custom(|info| {
  3.         eprintln!(
  4.             "{} {} {} {:?} from {} with {:?}",
  5.             info.method(),
  6.             info.path(),
  7.             info.status(),
  8.             info.elapsed(),
  9.             info.remote_addr().unwrap(),
  10.             info.request_headers()
  11.         )
  12.     });
  13. let routes = get_questions
  14.         .or(add_question)
  15.         .or(update_question)
  16.         .or(delete_question)
  17.         .or(add_answer)
  18.         .with(cors)
  19.         .with(log)
  20.         .recover(error::return_error);
  21. warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
复制代码
创建结构化的日志

  1. let log = warp::log::custom(|info| {
  2.         eprintln!(
  3.             "{} {} {} {:?} from {} with {:?}",
  4.             info.method(),
  5.             info.path(),
  6.             info.status(),
  7.             info.elapsed(),
  8.             info.remote_addr().unwrap(),
  9.             info.request_headers()
  10.         )
  11.     });
复制代码
日志跟踪

  1. tracing = {version = "0.1.40", features = ["log"]}
  2. tracing-subscriber = {version = "0.3.18", features = ["env-filter"]}
复制代码
  1. let log_filter =
  2.         std::env::var("RUST_LOG").unwrap_or_else(|_| "wrap_demo01=info,warp=error".to_owned());
  3.     tracing_subscriber::fmt()
  4.         .with_env_filter(log_filter)
  5.         .with_span_events(FmtSpan::CLOSE)
  6.         .init();
  7. // 针对某个请求设置跟踪
  8. let get_questions = warp::get()
  9.         .and(warp::path("questions"))
  10.         .and(warp::path::end())
  11.         .and(warp::query())
  12.         .and(store_filter.clone())
  13.         .and_then(get_questions)
  14.         .with(warp::trace(|info| {
  15.             tracing::info_span!("get_questions request", method = %info.method(),
  16.             path = %info.path(),
  17.             id = %uuid::Uuid::new_v4()) // 可根据 UUID 跟踪某个请求
  18.         }));
  19. // 记录每个传入的请求
  20. let routes = get_questions
  21.         .or(add_question)
  22.         .or(update_question)
  23.         .or(delete_question)
  24.         .or(add_answer)
  25.         .with(cors)
  26.         //.with(log)
  27.         .with(warp::trace::request())
  28.         .recover(error::return_error);
  29.     warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
  30. }
复制代码


  • 未设置 instrument​ , 单个请求有3条记载
    1. $ cargo run -p wrap_demo01 --bin wrap_demo01
    2. 2024-08-23T14:18:45.013769Z  INFO get_questions request{method=GET path=/questions id=5828015e-0289-47f1-9a26-16028f54dd3f}: wrap_demo01::routes::question: Querying questions
    3. 2024-08-23T14:18:45.013967Z  INFO get_questions request{method=GET path=/questions id=5828015e-0289-47f1-9a26-16028f54dd3f}: wrap_demo01::routes::question: pagination=false
    4. 2024-08-23T14:18:45.014083Z  INFO get_questions request{method=GET path=/questions id=5828015e-0289-47f1-9a26-16028f54dd3f}: wrap_demo01: close time.busy=355µs time.idle=45.9µs
    复制代码
  1. #[instrument]
  2. pub async fn get_questions(
  3.     params: HashMap<String, String>,
  4.     store: Store,
  5. ) -> Result<impl Reply, Rejection> {
  6.     info!("Querying questions");
  7.     match extract_pagination(params) {
  8.         Ok(pagination) => {
  9.             info!(pagination = true);
  10.             let questions = store.get(Some(pagination)).await;
  11.             Ok(warp::reply::json(&questions))
  12.         }
  13.         Err(_) => {
  14.             info!(pagination = false);
  15.             let questions = store.get(None).await;
  16.             Ok(warp::reply::json(&questions))
  17.         }
  18.     }
  19. }
复制代码


  • 设置 instrument​ 后, 单个请求有 4 条记载, 且提供更详细的信息
    1. $ cargo run -p wrap_demo01 --bin wrap_demo01
    2. 2024-08-23T14:22:46.631654Z  INFO get_questions request{method=GET path=/questions id=da967f3f-ff95-4dc0-bf17-935a38a863e8}:get_questions{params={} store=Store { questions: RwLock { data: {QuestionId("1"): Question { id: QuestionId("1"), title: "How?", content: "Please help!", tags: Some(["general"]) }} }, answers: RwLock { data: {} } }}: wrap_demo01::routes::question: Querying questions
    3. 2024-08-23T14:22:46.631765Z  INFO get_questions request{method=GET path=/questions id=da967f3f-ff95-4dc0-bf17-935a38a863e8}:get_questions{params={} store=Store { questions: RwLock { data: {QuestionId("1"): Question { id: QuestionId("1"), title: "How?", content: "Please help!", tags: Some(["general"]) }} }, answers: RwLock { data: {} } }}: wrap_demo01::routes::question: pagination=false
    4. 2024-08-23T14:22:46.631851Z  INFO get_questions request{method=GET path=/questions id=da967f3f-ff95-4dc0-bf17-935a38a863e8}:get_questions{params={} store=Store { questions: RwLock { data: {QuestionId("1"): Question { id: QuestionId("1"), title: "How?", content: "Please help!", tags: Some(["general"]) }} }, answers: RwLock { data: {} } }}: wrap_demo01::routes::question: close time.busy=212µs time.idle=9.73µs
    5. 2024-08-23T14:22:46.632025Z  INFO get_questions request{method=GET path=/questions id=da967f3f-ff95-4dc0-bf17-935a38a863e8}: wrap_demo01: close time.busy=520µs time.idle=87.6µs
    复制代码
日志调试


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

耶耶耶耶耶

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表