Struct flexi_logger::Logger
source · pub struct Logger { /* private fields */ }
Expand description
The entry-point for using flexi_logger
.
Logger
is a builder class that allows you to
-
specify your desired (initial) loglevel-specification
- either as a String (
Logger::try_with_str
) - or by providing it in the environment (
Logger::try_with_env
), - or by combining both options (
Logger::try_with_env_or_str
), - or by building a
LogSpecification
programmatically (Logger::with
),
- either as a String (
-
use the desired configuration methods,
-
and finally start the logger with
Logger::start
, or- [
Logger::start_with_specfile
].
Usage
See code_examples
for a comprehensive list of usage possibilities.
Implementations§
source§impl Logger
impl Logger
Create a Logger instance and define how to access the (initial) loglevel-specification.
sourcepub fn with(logspec: LogSpecification) -> Self
pub fn with(logspec: LogSpecification) -> Self
Creates a Logger that you provide with an explicit LogSpecification
.
sourcepub fn try_with_str<S: AsRef<str>>(s: S) -> Result<Self, FlexiLoggerError>
pub fn try_with_str<S: AsRef<str>>(s: S) -> Result<Self, FlexiLoggerError>
Creates a Logger that reads the LogSpecification
from a String
or &str
.
See LogSpecification
for the syntax.
Errors
FlexiLoggerError::Parse
if the String uses an erroneous syntax.
sourcepub fn try_with_env() -> Result<Self, FlexiLoggerError>
pub fn try_with_env() -> Result<Self, FlexiLoggerError>
Creates a Logger that reads the LogSpecification
from the environment variable
RUST_LOG
.
Note that if RUST_LOG
is not set, nothing is logged.
Errors
FlexiLoggerError::Parse
if the value of RUST_LOG
is malformed.
sourcepub fn try_with_env_or_str<S: AsRef<str>>(
s: S
) -> Result<Self, FlexiLoggerError>
pub fn try_with_env_or_str<S: AsRef<str>>( s: S ) -> Result<Self, FlexiLoggerError>
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.
Errors
FlexiLoggerError::Parse
if the chosen value is malformed.
source§impl Logger
impl Logger
Simple methods for influencing the behavior of the Logger.
sourcepub fn log_to_stderr(self) -> Self
pub fn log_to_stderr(self) -> Self
Log is written to stderr (which is the default).
sourcepub fn log_to_stdout(self) -> Self
pub fn log_to_stdout(self) -> Self
Log is written to stdout.
sourcepub fn log_to_file(self, file_spec: FileSpec) -> Self
pub fn log_to_file(self, file_spec: FileSpec) -> Self
Log is written to a file.
The default filename pattern is <program_name>_<date>_<time>.<suffix>
,
e.g. myprog_2015-07-08_10-44-11.log
.
You can duplicate to stdout and stderr, and you can add additional writers.
sourcepub fn log_to_writer(self, w: Box<dyn LogWriter>) -> Self
pub fn log_to_writer(self, w: Box<dyn LogWriter>) -> Self
Log is written to the provided writer.
You can duplicate to stdout and stderr, and you can add additional writers.
sourcepub fn log_to_file_and_writer(
self,
file_spec: FileSpec,
w: Box<dyn LogWriter>
) -> Self
pub fn log_to_file_and_writer( self, file_spec: FileSpec, w: Box<dyn LogWriter> ) -> Self
Log is written to a file, as with Logger::log_to_file
, and to an alternative
LogWriter
implementation.
And you can duplicate to stdout and stderr, and you can add additional writers.
sourcepub fn do_not_log(self) -> Self
pub fn do_not_log(self) -> Self
Log is processed, including duplication, but not written to any destination.
This can be useful e.g. for running application tests with all log-levels active and still avoiding tons of log files etc. Such tests ensure that the log calls which are normally not active will not cause undesired side-effects when activated (note that the log macros may prevent arguments of inactive log-calls from being evaluated).
Or, if you want to get logs both to stdout and stderr, but nowhere else,
then use this option and combine it with
Logger::duplicate_to_stdout
and Logger::duplicate_to_stderr
.
sourcepub fn print_message(self) -> Self
pub fn print_message(self) -> Self
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) -> Self
pub fn duplicate_to_stderr(self, dup: Duplicate) -> Self
Makes the logger write messages with the specified minimum severity additionally to stderr.
Does not work with Logger::log_to_stdout
or Logger::log_to_stderr
.
sourcepub fn duplicate_to_stdout(self, dup: Duplicate) -> Self
pub fn duplicate_to_stdout(self, dup: Duplicate) -> Self
Makes the logger write messages with the specified minimum severity additionally to stdout.
Does not work with Logger::log_to_stdout
or Logger::log_to_stderr
.
sourcepub fn format(self, format: FormatFunction) -> Self
pub fn format(self, format: FormatFunction) -> Self
Makes the logger use the provided format function for all messages that are written to files, stderr, stdout, or to an additional writer.
You can either choose one of the provided log-line formatters,
or you create and use your own format function with the signature
fn my_format(
write: &mut dyn std::io::Write,
now: &mut flexi_logger::DeferredNow,
record: &log::Record,
) -> std::io::Result<()>
By default, default_format
is used for output to files and to custom writers,
and AdaptiveFormat::Default
is used for output to stderr
and stdout
.
If the feature colors
is switched off, default_format
is used for all outputs.
sourcepub fn format_for_files(self, format: FormatFunction) -> Self
pub fn format_for_files(self, format: FormatFunction) -> Self
Makes the logger use the provided format function for messages that are written to files.
Regarding the default, see Logger::format
.
sourcepub fn format_for_stderr(self, format_function: FormatFunction) -> Self
pub fn format_for_stderr(self, format_function: FormatFunction) -> Self
Makes the logger use the provided format function for messages that are written to stderr.
Regarding the default, see Logger::format
.
sourcepub fn adaptive_format_for_stderr(self, adaptive_format: AdaptiveFormat) -> Self
pub fn adaptive_format_for_stderr(self, adaptive_format: AdaptiveFormat) -> Self
Makes the logger use the specified format for messages that are written to stderr
.
Coloring is used if stderr
is a tty.
Regarding the default, see Logger::format
.
sourcepub fn format_for_stdout(self, format_function: FormatFunction) -> Self
pub fn format_for_stdout(self, format_function: FormatFunction) -> Self
Makes the logger use the provided format function to format messages that are written to stdout.
Regarding the default, see Logger::format
.
sourcepub fn adaptive_format_for_stdout(self, adaptive_format: AdaptiveFormat) -> Self
pub fn adaptive_format_for_stdout(self, adaptive_format: AdaptiveFormat) -> Self
Makes the logger use the specified format for messages that are written to stdout
.
Coloring is used if stdout
is a tty.
Regarding the default, see Logger::format
.
sourcepub fn format_for_writer(self, format: FormatFunction) -> Self
pub fn format_for_writer(self, format: FormatFunction) -> Self
Allows specifying a format function for an additional writer. Note that it is up to the implementation of the additional writer whether it evaluates this setting or not.
Regarding the default, see Logger::format
.
sourcepub fn set_palette(self, palette: String) -> Self
pub fn set_palette(self, palette: String) -> Self
Sets the color palette for function style
, which is used in the
provided coloring format functions.
The palette given here overrides the default palette.
The palette is specified in form of a String that contains a semicolon-separated list
of numbers (0..=255) and/or dashes (´-´).
The first five values denote the fixed color that is
used for coloring error
, warn
, info
, debug
, and trace
messages.
The String "196;208;-;7;8"
describes the default palette, where color 196 is
used for error messages, and so on. The -
means that no coloring is done,
i.e., with "-;-;-;-;-"
all coloring is switched off.
Prefixing a number with ‘b’ makes the output being written in bold.
The String "b1;3;2;4;6"
e.g. describes the palette used by env_logger
.
The palette can further be overridden at runtime by setting the environment variable
FLEXI_LOGGER_PALETTE
to a palette String. This allows adapting the used text colors to
differently colored terminal backgrounds.
For your convenience, if you want to specify your own palette,
you can produce a colored list with all 255 colors with cargo run --example colors
.
sourcepub fn rotate(self, criterion: Criterion, naming: Naming, cleanup: Cleanup) -> Self
pub fn rotate(self, criterion: Criterion, naming: Naming, cleanup: Cleanup) -> Self
Prevent indefinite growth of the log file by applying file rotation and a clean-up strategy for older log files.
By default, the log file is fixed while your program is running and will grow indefinitely. With this option being used, when the log file reaches the specified criterion, the file will be closed and a new file will be opened.
Note that also the filename pattern changes:
- by default, no timestamp is added to the filename if rotation is used
- the logs are always written to a file with infix
_rCURRENT
- when the rotation criterion is fulfilled, it is closed and renamed to a file
with another infix (see
Naming
), and then the logging continues again to the (fresh) file with infix_rCURRENT
.
Example:
After some logging with your program my_prog
and rotation with Naming::Numbers
,
you will find files like
my_prog_r00000.log
my_prog_r00001.log
my_prog_r00002.log
my_prog_rCURRENT.log
Parameters
criterion
defines when the log file should be rotated, based on its size or age.
See Criterion
for details.
naming
defines the naming convention for the rotated log files.
See Naming
for details.
cleanup
defines the strategy for dealing with older files.
See Cleanup
for details.
sourcepub fn cleanup_in_background_thread(self, use_background_thread: bool) -> Self
pub fn cleanup_in_background_thread(self, use_background_thread: bool) -> Self
When Logger::rotate
is used with some Cleanup
variant other than Cleanup::Never
,
then this method can be used to define
if the cleanup activities (finding files, deleting files, evtl compressing files) are
delegated to a background thread (which is the default,
to minimize the blocking impact to your application caused by IO operations),
or whether they are done synchronously in the current log-call.
If you call this method with use_background_thread = false
,
the cleanup is done synchronously.
sourcepub fn filter(self, filter: Box<dyn LogLineFilter + Send + Sync>) -> Self
pub fn filter(self, filter: Box<dyn LogLineFilter + Send + Sync>) -> Self
Apply the provided filter before really writing log lines.
See the documentation of module filter
for a usage example.
sourcepub fn append(self) -> Self
pub fn append(self) -> Self
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 logs are written to files, but
it will hardly make an effect if FileSpec::suppress_timestamp
is not used.
sourcepub fn create_symlink<P: Into<PathBuf>>(self, symlink: P) -> Self
pub fn create_symlink<P: Into<PathBuf>>(self, symlink: P) -> Self
The specified path will be used on unix systems to create a symbolic link to the current log file.
This option has no effect on filesystems where symlinks are not supported, and it only has an effect if logs are written to files.
Example
You can use the symbolic link to follow the log output with tail
,
even if the log files are rotated.
Assuming you use create_symlink("link_to_log_file")
, then use:
tail --follow=name --max-unchanged-stats=1 --retry link_to_log_file
sourcepub fn add_writer<S: Into<String>>(
self,
target_name: S,
writer: Box<dyn LogWriter>
) -> Self
pub fn add_writer<S: Into<String>>( self, target_name: S, writer: Box<dyn LogWriter> ) -> Self
sourcepub fn write_mode(self, write_mode: WriteMode) -> Self
pub fn write_mode(self, write_mode: WriteMode) -> Self
Sets the write mode for the logger.
See WriteMode
for more (important!) details.
sourcepub fn use_windows_line_ending(self) -> Self
pub fn use_windows_line_ending(self) -> Self
Use Windows line endings, rather than just \n
.
sourcepub fn error_channel(self, error_channel: ErrorChannel) -> Self
pub fn error_channel(self, error_channel: ErrorChannel) -> Self
Define the output channel for flexi_logger
’s own error messages.
These are only written if flexi_logger
cannot do what it is supposed to do,
so under normal circumstances no single message shuld appear.
By default these error messages are printed to stderr
.
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_print_message(self, print_message: bool) -> Self
pub fn o_print_message(self, print_message: bool) -> Self
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_rotate(
self,
rotate_config: Option<(Criterion, Naming, Cleanup)>
) -> Self
pub fn o_rotate( self, rotate_config: Option<(Criterion, Naming, Cleanup)> ) -> Self
By default, and with None, the log file will grow indefinitely.
If a rotate_config
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.
The cleanup strategy allows delimiting the used space on disk.
sourcepub fn o_append(self, append: bool) -> Self
pub fn o_append(self, append: bool) -> Self
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 only has an effect if logs are written to files,
and it will hardly make an effect if suppress_timestamp()
is not used.
sourcepub fn o_create_symlink<P: Into<PathBuf>>(self, symlink: Option<P>) -> Self
pub fn o_create_symlink<P: Into<PathBuf>>(self, symlink: Option<P>) -> Self
If a String is specified, it will be used on unix systems to create in the current folder a symbolic link with this name to the current log file.
This option only has an effect on unix systems and if logs are written to files.
source§impl Logger
impl Logger
Finally, start logging, optionally with a spec-file.
sourcepub fn start(self) -> Result<LoggerHandle, FlexiLoggerError>
pub fn start(self) -> Result<LoggerHandle, FlexiLoggerError>
Consumes the Logger object and initializes flexi_logger
.
Keep the LoggerHandle
alive up to the very end of your program!
Dropping the LoggerHandle
flushes and shuts down FileLogWriter
s
and other LogWriter
s, and then may prevent further logging!
This should happen immediately before the program terminates, but not earlier.
Dropping the LoggerHandle
is uncritical
only with Logger::log_to_stdout
or Logger::log_to_stderr
.
The LoggerHandle
also allows updating the log specification programmatically,
e.g. to intensify logging for (buggy) parts of a (test) program, etc.
Example
use flexi_logger::{Logger,WriteMode, FileSpec};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let _logger = Logger::try_with_str("info")?
.log_to_file(FileSpec::default())
.write_mode(WriteMode::BufferAndFlush)
.start()?;
// ... do all your work and join back all threads whose logs you want to see ...
Ok(())
}
Errors
Several variants of FlexiLoggerError
can occur.
sourcepub fn build(self) -> Result<(Box<dyn Log>, LoggerHandle), FlexiLoggerError>
pub fn build(self) -> Result<(Box<dyn Log>, LoggerHandle), FlexiLoggerError>
Builds a boxed logger and a LoggerHandle
for it,
but does not initialize the global logger.
The returned boxed logger implements the Log
trait
and can be installed manually or nested within another logger.
Keep the LoggerHandle
alive up to the very end of your program!
See Logger::start
for more details.
Errors
Several variants of FlexiLoggerError
can occur.