2个不稳定版本
0.2.1 | 2023年9月21日 |
---|---|
0.1.1 | 2023年9月20日 |
0.1.0 |
|
#1564 in 编码
每月26次下载
11KB
234 行
带有JSON格式的日志记录器
json_log
帮助你在json
格式中打印日志。
用法
首先,在你的Cargo.toml
中添加这些
[dependencies]
log = { version = "0.4" }
json_log = { version = "0.1" }
serde = { version = "1", features = ["derive"] } # if you want to log your struct...
程序启动后,你需要选择日志级别。例如
use log::LevelFilter;
fn main() {
json_log::init_with_level(LevelFilter::Info).unwrap(); // use the `INFO` level.
}
或者,你可以设置环境变量RUST_LOG
fn main() {
// Note: set environment variable `RUST_LOG` to one of these (case insensitive):
let accepted_RUST_LOG = ["Trace", "Debug", "Info", "Warn", "Error"];
json_log::init_env().unwrap();
}
简单的文本日志
json_log
是log
trait的适配器。你可以在代码中使用所有log
功能。
例如
use log::LevelFilter;
use log::{debug, info, warn, error};
fn main() {
json_log::init_with_level(LevelFilter::Debug).unwrap();
let a = 1 + 2 + 3;
debug!("debug");
info!("a = {a}");
if a == 6 {
warn!("a is {}", a);
} else {
error!("unknown error: a should be {}, but got {a}", 6);
}
}
输出如下
{"level":"Debug","ts":1695181245461,"msg":"debug"}
{"level":"Info","ts":1695181245461,"msg":"a = 6"}
{"level":"Warn","ts":1695181245461,"msg":"a is 6"}
记录你的结构体
如果你已经定义了自己的日志结构体,你可以通过使其Serialize
来记录它。例如
use serde::Serialize;
#[derive(Serialize)]
struct MyLoggingStruct {
pub status: u16,
pub username: String,
pub method: String,
pub headers: std::collections::HashMap<String, String>,
}
// Or, ...
#[derive(Serialize)]
struct MyLoggingStructV2<'a> {
pub status: u16,
pub username: &'a str,
pub method: &'a str,
pub headers: std::collections::HashMap<&'a str, &'a str>,
}
然后,进行记录
use std::collections::HashMap;
use log::LevelFilter;
// A static reference, you can define it everywhere.
static MY_LOGGER: &json_log::JsonLogger = json_log::get_default_logger();
fn main() {
json_log::init_with_level(LevelFilter::Debug).unwrap(); // set to debug level
let data = MyLoggingStruct {
status: 404,
username: "My name is Jack".to_string(),
method: "ListMyMoney".to_string(),
headers: std::collections::HashMap::new(),
};
MY_LOGGER.info(&data);
}
更多示例请见./examples
。
依赖项
~0.7–1.5MB
~34K SLoC