log4rs输出json格式日志

toml

log = "0.4"
log4rs = "1.3"

rs

use log::{error, info, warn, LevelFilter};
use log4rs::{
    append::console::ConsoleAppender,
    config::{Appender, Root},
    encode::json::JsonEncoder,
};
use log4rs::append::file::FileAppender;

fn main() {
    //命令行
    let stdout = ConsoleAppender::builder()
        .encoder(Box::new(JsonEncoder::new()))
        .build();
    //文件
    let fileout = FileAppender::builder().
        encoder(Box::new(JsonEncoder::new())).
        build("./data.log").unwrap();
    let log_config = log4rs::config::Config::builder()
        .appender(Appender::builder().build("file", Box::new(fileout)))
        .build(Root::builder().appender("file").build(LevelFilter::Info))
        .unwrap();
    log4rs::init_config(log_config).unwrap();

    info!("Info log!");
    warn!("Warn log with value {}", "test");
    error!("ERROR!");
}
posted @ 2024-11-06 09:21  朝阳1  阅读(3)  评论(0编辑  收藏  举报