【问题标题】:How do I write to a virtual file in Rust?如何在 Rust 中写入虚拟文件?
【发布时间】:2022-10-14 23:04:12
【问题描述】:

假设我使用fern 设置了一个记录器,如下所示:

use log::{debug, error, info, trace, warn};

fn setup_logger() -> Result<(), log::SetLoggerError> {
    fern::Dispatch::new()
        .format(|out, message, record| {
            out.finish(format_args!(
                "{}[{}][{}] {}",
                chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
                record.target(),
                record.level(),
                message
            ))
        })
        .level(log::LevelFilter::Debug)
        .chain(std::io::stdout())
        .chain(fern::log_file("output.log")?) // (a)
        .apply()?;
    Ok(())
}

但是,我想用可选路径为setup_logger(log_path: Option&lt;std::path::PathBuf&gt;) 参数化这个setup_logger 函数。

因此,我想将上面的 (a) 行重写为:

// ...
.chain(match log_path {
    Some(path) => fern::log_file(path)?,
    None => // (b)
})
// ...

那么,我在上面的 (b) 行该怎么办?我已经尝试过std::io::sink,但是由于fern::log_file 返回了一个文件,所以匹配臂结果不兼容。

提前致谢。


环境

  • 锈 1.62.1

【问题讨论】:

    标签: rust


    【解决方案1】:

    使用中间值。

    fn setup_logger(log_path: Option<&str>) -> Result<(), log::SetLoggerError> {
        let mut logger = fern::Dispatch::new()
            .format(|out, message, record| {
                out.finish(format_args!(
                    "{}[{}][{}] {}",
                    chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
                    record.target(),
                    record.level(),
                    message
                ))
            })
            .level(log::LevelFilter::Debug)
            .chain(std::io::stdout());
    
        if let Some(log_path) = log_path {
            logger = logger.chain(fern::log_file("output.log")?);
        }
    
        logger.apply()?;
    
        Ok(())
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-09
      • 1970-01-01
      相关资源
      最近更新 更多