Log4rs is a highly configurable log library implemented by rust, which is configured in a flexible and relatively rich way to meet most of the project needs. GitHub Address: Https://github.com/sfackler/log4rs. Usage examples
Let's first give a simple example, and you can see from this example that log4rs is very flexible to log configuration:
#[macro_use]
extern crate log;
extern crate log4rs;
fn Main () {
log4rs::init_file ("Config/log4rs.yaml", Default::d efault ()). Unwrap ();
For i in 1..2{
info! (" Booting up {} ", I);
error! ("Error Test {}", i);
}
The log configuration file is as follows: (the file format is not unique, can be yaml,json,toml, and so on, the following is the YAML format of the configuration file)
# Scan This file to changes every seconds
refresh_rate:30 seconds
: # an
appenders appender "named" That's writes to stdout
stdout:
kind:console
# A appender named ' requests ' that's writes to a file with a Custo M Pattern Encoder
requests:
kind:file
path: "Log/requests.log"
encoder: Pattern
: "{D}-{m}{n}"
# Set The default logging level to ' info ' and attach the ' stdout ' appender to the root
root:
level:info
appenders:
-stdout
loggers:
# Raise The maximum log level for events sent to the "App::backend::d B" Lo Gger to ' info '
app::backend::d B:
level:info
# Route Log events sent to the ' app::requests ' logger to the ' Requests "Appender,
# and *not* the normal appenders installed at the root
app::requests:
level:info
appenders:
-Requests
Additive:false
Run Result:
Because the appenders configuration is stdout corresponding output to the console, so the log information output on the console, if the selection is requests, then the log information is exported to the corresponding path file.
Of course, the way the log is configured, in addition to the configuration file, can be configured in program code as follows:
extern crate log;
extern crate Log4rs;
Use Log::loglevelfilter;
Use Log4rs::append::console::consoleappender;
Use Log4rs::append::file::fileappender;
Use Log4rs::encode::p attern::P atternencoder;
Use Log4rs::config::{appender, config, Logger, Root};
fn Main () {Let stdout = Consoleappender::builder (). build (); Let requests = Fileappender::builder (). Encoder (Box::new (Patternencoder::new (' {d}-{m}{n} ')). Build ("Log
/requests.log "). Unwrap (); Let config = Config::builder (). Appender (Appender::builder (). Build ("stdout", Box::new (stdout)). Appender ( Appender::builder (). Build ("Requests", box::new (requests)). Logger (Logger::builder (). Build ("App::backend::d B", Lo
Glevelfilter::info)). Logger (Logger::builder (). Appender ("Requests"). Additive (FALSE) . Build ("App::requests", Loglevelfilter::info)). Builds (Root::builder (). Appender ("stdout"). Build (Loglevelfil Ter::warn)). Unwrap ();
Let handle = log4rs::init_config (config). Unwrap (); Configuration complete, the following output log information can//use handle to change logger configuration at runtime}//Can see the way the code is more cumbersome, so recommend the use of configuration files, procedures concise, easy to modify, with Flexible, he le AH.
Log4rs has the above two configuration forms, the function is as follows: Init_config--initializes the global logger as a log4rs logger with the provided config. (through code configuration) I Nit_file--initializes the global logger as a LOG4RS logger configured via a file. (via profile configuration)
In fact, the Init_file function implementation of the internal call of the Init_config function, that is, through the read configuration file through the serialization of Config, and then call Init_config. (Source code: HTTPS://DOCS.RS/LOG4RS/0.7.0/SRC/LOG4RS/PRIV_FILE.RS.HTML#23-51)
Through the program configuration better understanding, through the configuration file, there is a certain format and definition requirements, YAML,JSON,TOML, etc. to be in accordance with certain rules to generate the correct configuration file, the following in the YAML format as an example:
# If Set, log4rs'll scan the file at the specified rate for changes and # automatically reconfigure the logger.
The input string is parsed by the # Humantime crate. Refresh_rate:30 seconds# profile refresh rate, it can be understood that the configuration file is re-read every 30s again # the "Appenders" map contains the set of Appenders, indexed by T
Heir names. Appenders:foo: # All appenders must specify a "kind", which'll be used to look up the # logic to construct
The Appender in the ' deserializers ' passed to the # deserialization function.
Kind:console # Filters attached to a appender are specified inside the ' Filters ' # array.
Filters:-Appenders, filters are identified by their "kind". Kind:threshold # The remainder of the configuration is passed along to the # filter ' s builder, and would
Vary based on the kind of filter. Level:error # The remainder of the configuration is passed along to the Appender ' s # Builder, and'll vary base D on the Kind of appender.
# appenders would commonly be associated with a encoder.
Encoder: # like Appenders, encoders are identified by their ' kind '. # # Default:pattern Kind:pattern # The remainder of the configuration is passed along to the #
Encoder ' s builder, and'll vary based on the kind of encoder.
Pattern: ' {d} [{T}] {m}{n} ' # The root logger is configured by the ' root ' map.
Root: # The maximum log level is for the root logger.
# # Default:warn Level:warn # The list of appenders attached to the root logger. # default:empty list appenders:-Foo # the "loggers" map contains the set of configured loggers, indexed by T
Heir # names.
Loggers:foo::bar::baz: # The maximum log level.
# # Default:parent Logger ' s level level:trace # The list of appenders attached to the logger. # # Default:empty list appenders:-Foo # The additivity of the logger. If true, AppenDERs attached to the logger ' s # parent would also be attached to this logger. # default:true Additive:false
With the above example, the basic usage is almost the following, continue to learn more about log4rs. Log4rs
The log4rs consists of 4 parts: Appenders, encoders, filters, and loggers. Appenders--an Appender takes a log and logs it somewhere, for example, to a file, the console, or the syslog. Encoders--an Encoder is responsible to taking a log record, transforming it into the appropriate output format, and WRI Ting it out. An appender would normally use a encoder internally. Filters--filters are associated with appenders and, like the name would suggest, filter log events coming to that AppE NDEr. Loggers--a Log event is targeted at A specific logger, which are to identified by string names. Appenders
An appender takes a log and logs it somewhere, for example, to a file, the console, or the syslog.
Appenders mainly has the following three kinds: Console--the console appender. (Output to console) file--the file Appender. (Output to file) rolling_file--a rolling file Appender. (Implement file rollback)
The output to the console, the output to the file, the implementation of file rollback and other functions. One of the more complex is rolling_file, which is commonly used in our engineering, such as the implementation of the log size control (control log file size of 10MB, to 10MB, automatically empty the log, restart the record), to achieve the control of the number of log files (limit the number of simultaneous restrictions on individual file size Wait Here's a Rolling_file sample program to illustrate its usage.
The following program implements the ability to limit the log file size to 1024Byte.
#[macro_use]
extern crate log;
extern crate log4rs;
Use std::d efault::D efault;
Use Std::thread;
Use std::time::D uration;
fn Main () {
log4rs::init_file ("Config/log4rs.yaml", Default::d efault ()). Unwrap ();
For i in 1..2{
info! (" Booting up {} ", I);
error! ("Error Test {}", i);
}
Infinite loop, constantly log
loop{
thread::sleep (duration::from_secs (1));
Info! ("booting Up");
error! ("Error Test");
}
The focus is on configuration files, with different configurations to achieve different functions:
Appenders:
stdout:
kind:console
requests:
kind:file
path: "Requests.log"
encoder:
Pattern: "{d} [{T}] {L} {m}:{m}{n}"
##################################################
Roll: #定义rooling_ File's appenders
kind:rolling_file
path: "Roll.log"
append:true
encoder:
kind:pattern
policy:
kind:compound
Trigger:
kind:size
limit:1024 #限制大小为1024Byte
Roller:
kind:delete# rollback for direct deletion
##################################################
root:
level:info
Appenders:
-roll# Use roll appenders
loggers:
app::backend::d B:
level:info app::requests
:
level:info
appenders:
-Requests
Additive:false
Another configuration reference code that restricts the size of the log file and limits the number of log files:
#yaml文件
appenders:
foo: #限制日志文件大小的配置
kind:rolling_file
path: {0}/foo.log
policy:
Trigger :
kind:size
limit:1024
Roller:
kind:delete
bar: #限制日志文件数量的配置
kind:rolling_file
Path: {0}/foo.log
policy:
kind:compound
Trigger:
kind:size
limit:5 MB
Roller:
Kind:fixed_window pattern
: ' {0}/foo.log.{ {}} '
base:1
count:5
Explanation of the corresponding configuration item:
///# Configuration//////' yaml///kind:rolling_file//////# The path of the ' log file '.
Required. Path:log/foo.log//////# Specifies if the appender should append to or truncate the log file if it///# already ex Ists.
Defaults to ' true '. Append:true//////# The encoder to use to format output.
Defaults to ' Kind:pattern '. Encoder:///kind:pattern//////# The policy which the handles of the log file.
Required. Policy:///# identifies which policy is to be used.
If No kind is specified, it would///# default to ' compound '. Kind:compound//////# The remainder of the configuration is passed along to the policy ' s///# Deserializer,
And would vary based on the kind of policy. Trigger:///kind:size///limit:10 mb//////Roller:///kind:delete '
Why is this configuration, or, where these configuration items come from, it is necessary to analyze the source code, take Rolling_file as an example:
The rolling_file contains 5 structural bodies, respectively: Logfile--information about the active log file. Rollingfileappender--an Appender which archives log files in a configurable strategy. Rollingfileappenderbuilder--a Builder for the Rollingfileappender. Rollingfileappenderconfig--configuration for the rolling file appender. Rollingfileappenderdeserializer--a Deserializer for the Rollingfileappender.
Configuration for the rolling file appender.
Pub struct Rollingfileappenderconfig {
path:string,
append:option<bool>,
encoder:option< Encoderconfig>,
policy:policy,
}
This lists the configuration items that the Rolling_file Appender needs, and the other configuration is in ***config, the same reason. Encoders
An encoder was responsible for taking a log record, transforming it into the appropriate output format, and writing it out.
Encoders consists of three main parts: Json--an encoder which writes a JSON object. Pattern--a Simple pattern-based Encoder. Writer--implementations of the encode::write trait.
The most commonly used is pattern, so focus on the analysis of pattern. This is similar to the other language of the formatter or log attributes, and other concepts, from the official document truncated map, Link: https://docs.rs/log4rs/0.7.0/log4rs/encode/pattern/index.html
More not detailed, according to their own needs, to see the official documents.