Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· openaiHugging Face Suzhen/CodeChat

rust tracing crate 不同进程写入不同文件,同时显示文件名和行号

  1. User

    rust tracing crate 不同进程写入不同文件,同时显示文件名和行号

  2. Assistant

    Rust 的 tracing crate 是一个用于结构化日志记录和跟踪事件的框架。如果您想要不同的进程将日志写入不同的文件,并同时显示在日志中的文件名和行号,您可以按照以下步骤来实现:

    1. 添加 tracing 和 tracing-subscriber 依赖到您的 Cargo.toml 文件中:

      [dependencies]
      tracing = "0.1"
      tracing-subscriber = "0.3"
      
    2. 在每个进程的入口处(main 函数或等效的启动代码中)设置 'tracing' 订阅者,并配置它以将日志输出到不同的文件,并包括文件名和行号:

      use tracing::{info, Level};
      use tracing_subscriber::fmt::{self, format::FmtSpan};
      use tracing_subscriber::EnvFilter;
      
      fn main() {
          // 根据进程产生一个日志文件名
          let file_name = format!("process-{}.log", std::process::id());
      
          // 设置日志的格式化层和过滤层
          let file_appender = tracing_appender::rolling::never(".", &file_name);
          let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
      
          tracing_subscriber::fmt()
              .with_writer(non_blocking)
              .with_max_level(Level::TRACE) // 设置日志级别
               // 显示目标、级别、线程ID、文件和行号
              .with_target(true)
              .with_thread_ids(true)
              .with_thread_names(true)
              .with_file(true)
              .with_line_number(true)
              .with_span_events(FmtSpan::CLOSE)
              .init();
      
          // 使用示例
          info!(target: "my_app", "Starting process with ID {}", std::process::id());
          // ...
      }
      

      上面的代码展示了如何为进程设置一个日志订阅者 (Subscriber)。这里使用的是非阻塞的日志写入器,将日志异步写入到文件。

    3. 现在,在您的应用代码中使用 tracing 宏,在需要记录日志的位置:

      use tracing::{info, warn, error};
      
      fn my_function() {
          info!("This is an information message with a number: {}", 42);
          warn!(file= file!(), line= line!(), "This is a warning with file and line number");
          error!("An error occurred!");
      }
      

    使用 tracing 的 info!、warn! 和 error! 宏可以产生不同级别的日志条目。它们会自动包含代码中的文件和行号信息,除非您显式地指定其他值如宏 file!() 和 line!() 所示。

    通过上述的配置,每个进程会将其日志数据写入独立的文件,并在日志中展示文件名和行号。记得为不同的进程生成或指定不同的日志文件名,以避免混淆和覆盖。

  3. User

    use tracing_subscriber::EnvFilter 没有

  4. Assistant

    非常抱歉,我的上一条回答中有些指导是不准确的。由于您想要使用 tracing 和 tracing_subscriber 来进行进程间的日志记录,我应该为您提供更准确的代码示例。以下是正确的步骤和代码示例:

    1. 在 Cargo.toml 添加 tracing 和 tracing_subscriber 依赖:

      [dependencies]
      tracing = "0.1"
      tracing-subscriber = "0.3"
      
    2. 调整您的设置和初始化代码如下:

      use tracing::info;
      use tracing_subscriber::fmt::format::FmtSpan;
      use tracing_subscriber::fmt::writer::MakeWriterExt;
      use tracing_subscriber::fmt::{self};
      use std::io;
      
      fn main() {
          let process_id = std::process::id();
          let file_name = format!("process-{}.log", process_id);
      
          // 创建自定义的写入器(MakeWriter)
          let file_appender = tracing_appender::rolling::never(".", &file_name);
          let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
      
          // 设置格式化层,包括文件名和行号
          let subscriber = tracing_subscriber::fmt()
              .with_writer(non_blocking)
              .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) // 使用环境变量来设置过滤器
              .with_file(true)
              .with_line_number(true)
              .with_thread_ids(true)
              .with_span_events(FmtSpan::CLOSE)
              .finish();
      
          // 设置订阅者
          tracing::subscriber::set_global_default(subscriber).expect("Unable to set global subscriber");
      
          // 使用示例
          info!(target: "my_app", "Starting process with ID {}", process_id);
          // ...
      }
      

    在这个例子中,我使用了 tracing_appender::non_blocking 来创建一个异步日志写入器。此外,通过搭配环境变量 RUST_LOG,您可以轻松地控制日志的过滤级别。您只需要在环境变量中设置相应的值,例如 RUST_LOG=info 或者 RUST_LOG=my_app=trace。

    在程序代码中,您可以像通常那样使用各种 tracing 宏来记录信息。

    如果您有任何进一步的问题,或者需要更多帮助,请随时提问。

  5. User

    could not find EnvFilter in tracing_subscriber

  6. Assistant

    I apologize for the confusion. The EnvFilter is part of the tracing_subscriber crate, and sometimes, it may not be recognized due to missing imports or a version mismatch in the dependencies. As of the latest stable versions at the time of the knowledge cutoff in 2023, the EnvFilter should be accessible.

    First, please ensure that you have the latest compatible versions of tracing and tracing-subscriber in your Cargo.toml file:

    [dependencies]
    tracing = "0.1"
    tracing-subscriber = "0.3"
    tracing-appender = "0.2"
    

    Then, import the EnvFilter directly from the tracing_subscriber::filter module:

    use tracing::info;
    use tracing_appender::non_blocking;
    use tracing_subscriber::fmt;
    use tracing_subscriber::filter::EnvFilter;
    
    fn main() {
        // Your file_name generation code here
    
        // Create a non-blocking, asynchronously-flushing file appender
        let file_appender = tracing_appender::rolling::never(".", &file_name);
        let (non_blocking_writer, _guard) = non_blocking(file_appender);
    
        // Create a `tracing` subscriber with the `fmt` layer and `EnvFilter` layer
        let subscriber = fmt()
            .with_writer(non_blocking_writer)
            .with_env_filter(EnvFilter::from_default_env()) // Retrieve filter directive from RUST_LOG env var
            .with_file(true)  // Include source file information
            .with_line_number(true) // Include line numbers
            .finish();
    
        // Set the subscriber as the global default
        tracing::subscriber::set_global_default(subscriber)
            .expect("Failed to set global default subscriber");
    
        // Example log statement
        info!(target: "my_app", "Starting process with ID {}", std::process::id());
    
        // The rest of your application logic
    }
    

    Make sure that you include the tracing-appender crate if you're using a file appender and that you've imported all necessary modules and traits. This code sets up a subscriber with a non-blocking file appender and an environment filter that uses the RUST_LOG environment variable for log filtering rules.

    Now, when you run your application, you can control the log level by setting the RUST_LOG environment variable:

    RUST_LOG=info cargo run
    

    or on Windows (using Command Prompt):

    set RUST_LOG=info
    cargo run
    

    This will filter the logs according to the level specified in the RUST_LOG variable.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.