Struct flexi_logger::Logger
source · pub struct Logger { /* private fields */ }
Expand description
The entry-point for using flexi_logger
.
A simple example with file logging might look like this:
use flexi_logger::{Duplicate,Logger};
Logger::with_str("info, mycrate = debug")
.log_to_file()
.duplicate_to_stderr(Duplicate::Warn)
.start()
.unwrap_or_else(|e| panic!("Logger initialization failed with {}", e));
Logger
is a builder class that allows you to
-
specify your desired (initial) loglevel-specification
- either programmatically as a String
(
Logger::with_str()
) - or by providing a String in the environment
(
Logger::with_env()
), - or by combining both options
(
Logger::with_env_or_str()
), - or by building a
LogSpecification
programmatically (Logger::with()
),
- either programmatically as a String
(
-
use the desired configuration methods,
-
and finally start the logger with
Implementations§
source§impl Logger
impl Logger
Choose a way to create a Logger instance and define how to access the (initial) loglevel-specification.
sourcepub fn with(logspec: LogSpecification) -> Logger
pub fn with(logspec: LogSpecification) -> Logger
Creates a Logger that you provide with an explicit LogSpecification.
By default, logs are written with default_format
to stderr
.
sourcepub fn with_str<S: AsRef<str>>(s: S) -> Logger
pub fn with_str<S: AsRef<str>>(s: S) -> Logger
Creates a Logger that reads the LogSpecification from a String or &str. See LogSpecification for the syntax.
sourcepub fn with_env() -> Logger
pub fn with_env() -> Logger
Creates a Logger that reads the LogSpecification from the environment variable RUST_LOG.
sourcepub fn with_env_or_str<S: AsRef<str>>(s: S) -> Logger
pub fn with_env_or_str<S: AsRef<str>>(s: S) -> Logger
Creates a Logger that reads the LogSpecification from the environment variable RUST_LOG, or derives it from the given String, if RUST_LOG is not set.
source§impl Logger
impl Logger
Choose a way how to start logging.
sourcepub fn start(self) -> Result<(), FlexiLoggerError>
pub fn start(self) -> Result<(), FlexiLoggerError>
Consumes the Logger object and initializes flexi_logger
.
If started this way, the logger cannot be influenced anymore while the program is running. This is what you want in most of the cases.
sourcepub fn start_reconfigurable(
self
) -> Result<ReconfigurationHandle, FlexiLoggerError>
pub fn start_reconfigurable(
self
) -> Result<ReconfigurationHandle, FlexiLoggerError>
Consumes the Logger object and initializes flexi_logger
in a way that
subsequently the log specification can be updated programmatically.
This allows e.g. to intensify logging for (buggy) parts of a (test) program, etc.
use flexi_logger::Logger;
let mut logger_handle = Logger::with_str("info")
.start_reconfigurable()
.unwrap_or_else(|e| panic!("Logger initialization failed with {}", e));
// ...
// intensify logging
logger_handle.parse_new_spec("trace");
// ... critical stuff happens here ...
// switch logging back to normal
logger_handle.parse_new_spec("info");
// ...
The resulting logger is still fast, but measurable slower for those log-calls (trace!() etc) that are on a deeper level than the deepest level in the LogSpecification. This is because the Log crate has an optimization for returning very fast from deep-level log calls, but the deepest level needs be given at initialization and cannot be updated later.
Here is the output from a benchmark test, runnning on a windows laptop:
1 PS C:\projects\flexi_logger> cargo bench --bench bench_standard -- --nocapture
2 Finished release [optimized] target(s) in 0.4 secs
3 Running target\release\deps\bench_standard-20539c2be6d4f2e0.exe
4
5 running 4 tests
6 test b10_no_logger_active ... bench: 118 ns/iter (+/- 19)
7 test b20_initialize_logger ... bench: 0 ns/iter (+/- 0)
8 test b30_relevant_logs ... bench: 291,436 ns/iter (+/- 44,658)
9 test b40_suppressed_logs ... bench: 123 ns/iter (+/- 5)
10
11 test result: ok. 0 passed; 0 failed; 0 ignored; 4 measured; 0 filtered out
12
13 PS C:\projects\flexi_logger> cargo bench --bench bench_reconfigurable -- --nocapture
14 Finished release [optimized] target(s) in 0.4 secs
15 Running target\release\deps\bench_reconfigurable-2e292a8d5c887d0d.exe
16
17 running 4 tests
18 test b10_no_logger_active ... bench: 130 ns/iter (+/- 37)
19 test b20_initialize_logger ... bench: 0 ns/iter (+/- 0)
20 test b30_relevant_logs ... bench: 301,092 ns/iter (+/- 87,452)
21 test b40_suppressed_logs ... bench: 3,482 ns/iter (+/- 339)
22
23 test result: ok. 0 passed; 0 failed; 0 ignored; 4 measured; 0 filtered out
It shows that logging is fastest when no logger is active (lines 6 and 18). And it is just as fast when the above-mentioned optimization kicks in (line 9).
Logging has measurable costs when logs are really written (line 8 and 20), independent of the reconfigurability feature of the flexi_logger.
The measurable, but still in most cases not important, price for reconfigurability can be seen by comparing lines 9 and 21.
sourcepub fn start_with_specfile<P: AsRef<Path>>(
self,
specfile: P
) -> Result<(), FlexiLoggerError>
pub fn start_with_specfile<P: AsRef<Path>>(
self,
specfile: P
) -> Result<(), FlexiLoggerError>
Consumes the Logger object and initializes flexi_logger
in a way that
subsequently the log specification can be updated manually.
Uses the spec that was given to the factory method (Logger::with()
etc)
as initial spec and then tries to read the logspec from a file.
If the file does not exist, flexi_logger
creates the file and fills it
with the initial spec (and in the respective file format, of course).
Feature dependency
The implementation of this configuration method uses some additional crates
that you might not want to depend on with your program if you don’t use this functionality.
For that reason the method is only available if you activate the
specfile
feature. See flexi_logger
’s usage section for details.
Usage
A logger initialization like
use flexi_logger::Logger;
Logger::with_str("info")/*...*/.start_with_specfile("logspecification.toml");
will create the file logspecification.toml
(if it does not yet exist) with this content:
## Optional: Default log level
global_level = 'info'
## Optional: specify a regular expression to suppress all messages that don't match
#global_pattern = 'foo'
## Specific log levels per module are optionally defined in this section
[modules]
#'mod1' = 'warn'
#'mod2' = 'debug'
#'mod2::mod3' = 'trace'
You can subsequently edit and modify the file according to your needs, while the program is running, and it will immediately take your changes into account.
Currently only toml-files are supported, the file suffix thus must be .toml
.
The initial spec remains valid if the file cannot be read.
If you update the specfile subsequently while the program is running, flexi_logger
re-reads it automatically and adapts its behavior according to the new content.
If the file cannot be read anymore, e.g. because the format is not correct, the
previous logspec remains active.
If the file is corrected subsequently, the log spec update will work again.
source§impl Logger
impl Logger
Simple methods for influencing the behavior of the Logger.
sourcepub fn log_to_file(self) -> Logger
pub fn log_to_file(self) -> Logger
Makes the logger write all logs to a file, rather than to stderr.
The default pattern for the filename is ‘<program_name>_<date>_<time>.<suffix>’,
e.g. myprog_2015-07-08_10-44-11.log
.
sourcepub fn print_message(self) -> Logger
pub fn print_message(self) -> Logger
Makes the logger print an info message to stdout with the name of the logfile when a logfile is opened for writing.
sourcepub fn duplicate_to_stderr(self, dup: Duplicate) -> Logger
pub fn duplicate_to_stderr(self, dup: Duplicate) -> Logger
Makes the logger write messages with the specified minimum severity additionally to stderr.
sourcepub fn duplicate_error(self) -> Logger
👎Deprecated: use duplicate_to_stderr(dup: Duplicate)
pub fn duplicate_error(self) -> Logger
Makes the logger write all logged error messages additionally to stderr.
sourcepub fn duplicate_info(self) -> Logger
👎Deprecated: use duplicate_to_stderr(dup: Duplicate)
pub fn duplicate_info(self) -> Logger
Makes the logger write all logged error, warning, and info messages additionally to stderr.
sourcepub fn format(self, format: FormatFunction) -> Logger
pub fn format(self, format: FormatFunction) -> Logger
Makes the logger use the provided format function for the log entries, rather than formats::default_format.
You can either choose between some predefined variants,
default_format
, opt_format
, detailed_format
, with_thread
,
or you create and use your own format function
with the signature fn(&Record) -> String
.
sourcepub fn directory<S: Into<String>>(self, directory: S) -> Logger
pub fn directory<S: Into<String>>(self, directory: S) -> Logger
Specifies a folder for the log files.
This parameter only has an effect if log_to_file()
is used, too.
If the specified folder does not exist, the initialization will fail.
By default, the log files are created in the folder where the program was started.
sourcepub fn suffix<S: Into<String>>(self, suffix: S) -> Logger
pub fn suffix<S: Into<String>>(self, suffix: S) -> Logger
Specifies a suffix for the log files.
This parameter only has an effect if log_to_file()
is used, too.
sourcepub fn suppress_timestamp(self) -> Logger
pub fn suppress_timestamp(self) -> Logger
Makes the logger not include a timestamp into the names of the log files.
This option only has an effect if log_to_file()
is used, too.
sourcepub fn rotate_over_size(self, rotate_over_size: usize) -> Logger
pub fn rotate_over_size(self, rotate_over_size: usize) -> Logger
By default, the log file will grow indefinitely. With this option, when the log file reaches or exceeds the specified file size, the file will be closed and a new file will be opened. Also the filename pattern changes: instead of the timestamp, a serial number is included into the filename.
The size is given in bytes, e.g. rotate_over_size(1_000)
will rotate
files once they reach a size of 1 kB.
This option only has an effect if log_to_file()
is used, too.
sourcepub fn append(self) -> Logger
pub fn append(self) -> Logger
Makes the logger append to the specified output file, if it exists already; by default, the file would be truncated.
This option only has an effect if log_to_file()
is used, too.
This option will hardly make an effect if suppress_timestamp()
is not used.
sourcepub fn discriminant<S: Into<String>>(self, discriminant: S) -> Logger
pub fn discriminant<S: Into<String>>(self, discriminant: S) -> Logger
The specified String is added to the log file name after the program name.
This option only has an effect if log_to_file()
is used, too.
sourcepub fn create_symlink<S: Into<String>>(self, symlink: S) -> Logger
pub fn create_symlink<S: Into<String>>(self, symlink: S) -> Logger
The specified String will be used on linux systems to create in the current folder a symbolic link to the current log file.
This option only has an effect if log_to_file()
is used, too.
source§impl Logger
impl Logger
Alternative set of methods to control the behavior of the Logger.
Use these methods when you want to control the settings flexibly,
e.g. with commandline arguments via docopts
or clap
.
sourcepub fn o_log_to_file(self, log_to_file: bool) -> Logger
pub fn o_log_to_file(self, log_to_file: bool) -> Logger
With true, makes the logger write all logs to a file, otherwise to stderr.
sourcepub fn o_print_message(self, print_message: bool) -> Logger
pub fn o_print_message(self, print_message: bool) -> Logger
With true, makes the logger print an info message to stdout, each time when a new file is used for log-output.
sourcepub fn o_duplicate_error(self, duplicate_error: bool) -> Logger
👎Deprecated: use duplicate_to_stderr(dup: Duplicate)
pub fn o_duplicate_error(self, duplicate_error: bool) -> Logger
With true, makes the logger write all logged error messages additionally to stderr; with false, no messages are duplicated.
sourcepub fn o_duplicate_info(self, duplicate_info: bool) -> Logger
👎Deprecated: use duplicate_to_stderr(dup: Duplicate)
pub fn o_duplicate_info(self, duplicate_info: bool) -> Logger
With true, makes the logger write all logged error, warning, and info messages additionally to stderr; with false, no messages are duplicated.
sourcepub fn o_directory<S: Into<String>>(self, directory: Option<S>) -> Logger
pub fn o_directory<S: Into<String>>(self, directory: Option<S>) -> Logger
Specifies a folder for the log files.
This parameter only has an effect if log_to_file
is set to true.
If the specified folder does not exist, the initialization will fail.
With None, the log files are created in the folder where the program was started.
sourcepub fn o_rotate_over_size(self, rotate_over_size: Option<usize>) -> Logger
pub fn o_rotate_over_size(self, rotate_over_size: Option<usize>) -> Logger
This option only has an effect if log_to_file
is set to true.
By default, and with None, the log file will grow indefinitely. If a size is set, when the log file reaches or exceeds the specified size, the file will be closed and a new file will be opened. Also the filename pattern changes: instead of the timestamp, a serial number is included into the filename.
The size is given in bytes, e.g. o_rotate_over_size(Some(1_000))
will rotate
files once they reach a size of 1 kB.
sourcepub fn o_timestamp(self, timestamp: bool) -> Logger
pub fn o_timestamp(self, timestamp: bool) -> Logger
With true, makes the logger include a timestamp into the names of the log files.
true
is the default, but rotate_over_size
sets it to false
.
With this method you can set it to true
again.
This parameter only has an effect if log_to_file
is set to true.
sourcepub fn o_append(self, append: bool) -> Logger
pub fn o_append(self, append: bool) -> Logger
This option only has an effect if log_to_file
is set to true.
If append is set to true, makes the logger append to the specified output file, if it exists. By default, or with false, the file would be truncated.
This option will hardly make an effect if suppress_timestamp()
is not used.