引入crate:
log4rs = {version = "1.3.0"} log = {version = "0.4.20"}
配置文件
和Cargo.toml同级创建log4rs.yml,内容如下:
refresh_rate: 30 seconds
appenders:stdout:kind: consolerollingfile:kind: rolling_filepath: logs/app.logencoder:pattern: "[{d(%Y-%m-%dT%H:%M:%S%.6f)} {h({l}):<5.5} {M} threadID:{I}] {m}{n}"policy:trigger:kind: sizelimit: 10mbroller:kind: fixed_windowpattern: "logs/app-{}.log"count: 5base: 1root:level: infoappenders:- stdout- rollingfile
测试代码
extern crate log;
extern crate log4rs;use log::{info,error};
use std::thread;#[tokio::main]
async fn main() -> io::Result<()> {log4rs::init_file("log4rs.yml", Default::default()).unwrap();info!("hello log4rs");error!("this is error message!");let t1 = thread::spawn(||{info!("this message is output by sub thead!");error!("从子线程里输出的错误信息");});t1.join();Ok(())
}
配置说明
d, date - The current time. By default, the ISO 8601 format is used. A custom format may be provided in the syntax accepted by chrono. The timezone defaults to local, but can be specified explicitly by passing a second argument of utc for UTC or local for local time.
{d} - 2016-03-20T14:22:20.644420340-08:00
{d(%Y-%m-%d %H:%M:%S)} - 2016-03-20 14:22:20
{d(%Y-%m-%d %H:%M:%S %Z)(utc)} - 2016-03-20 22:22:20 UTC
f, file - The source file that the log message came from, or ??? if not provided.
h, highlight - Styles its argument according to the log level. The style is intense red for errors, red for warnings, blue for info, and the default style for all other levels.
{h(the level is {l})} - the level is ERROR
l``, level - The log level.
L, line - The line that the log message came from, or ??? if not provided.
m, message - The log message.
M, module - The module that the log message came from, or ??? if not provided.
n - A platform-specific newline.
t, target - The target of the log message.
T, thread - The name of the current thread.
I, thread_id - The ID of the current thread.
X, mdc - A value from the MDC. The first argument specifies the key, and the second argument specifies the default value if the key is not present in the MDC. The second argument is optional, and defaults to the empty string.
{X(user_id)} - 123e4567-e89b-12d3-a456-426655440000
{X(nonexistent_key)(no mapping)} - no mapping
An "unnamed" formatter simply formats its argument, applying the format specification.
{({l} {m})} - INFO hello
输出效果
[2024-03-15T23:08:43.434750 INFO helloworld threadID:20052] hello log4rs
[2024-03-15T23:08:43.434990 ERROR helloworld threadID:20052] this is error message!
[2024-03-15T23:08:43.435304 INFO helloworld threadID:18732] this message is output by sub thead!
[2024-03-15T23:08:43.435507 ERROR helloworld threadID:18732] 从子线程里输出的错误信息
[2024-03-15T23:08:43.436489 INFO helloworld threadID:20052] {"age":43,"name":"henreash","phone":["+44-012345","+44-0123456"]}