Struct flexi_logger::Logger [−][src]
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
impl Logger
[src]
Create a Logger instance and define how to access the (initial) loglevel-specification.
#[must_use]pub fn with(logspec: LogSpecification) -> Self
[src]
Creates a Logger that you provide with an explicit LogSpecification
.
By default, logs are written with default_format
to stderr
.
#[must_use]pub fn with_str<S: AsRef<str>>(s: S) -> Self
[src]
Creates a Logger that reads the LogSpecification
from a String or &str.
See LogSpecification
for the syntax.
#[must_use]pub fn with_env() -> Self
[src]
Creates a Logger that reads the LogSpecification
from the environment variable RUST_LOG
.
#[must_use]pub fn with_env_or_str<S: AsRef<str>>(s: S) -> Self
[src]
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.
impl Logger
[src]
Simple methods for influencing the behavior of the Logger.
pub fn check_parser_error(self) -> Result<Self, FlexiLoggerError>
[src]
Allows verifying that no parsing errors have occured in the used factory method, and examining the parse error.
Most of the factory methods for Logger (Logger::with_...()
)
parse a log specification String, and deduce from it a LogSpecification
object.
If parsing fails, errors are reported to stdout, but effectively ignored.
In worst case, nothing is logged!
This method gives programmatic access to parse errors, if there were any, so that errors don’t happen unnoticed.
In the following example we just panic if the spec was not free of errors:
Logger::with_str("hello world") .check_parser_error() .unwrap() // <-- here we could do better than panic .log_target(LogTarget::File) .start();
Errors
FlexiLoggerError::Parse
if the input for the log specification is malformed.
#[must_use]pub fn log_to_file(self) -> Self
[src]
Is equivalent to
log_target
(
LogTarget::File
)
.
#[must_use]pub fn log_target(self, log_target: LogTarget) -> Self
[src]
Write the main log output to the specified target.
By default, i.e. if this method is not called,
the log target LogTarget::StdErr
is used.
#[must_use]pub fn print_message(self) -> Self
[src]
Makes the logger print an info message to stdout with the name of the logfile when a logfile is opened for writing.
#[must_use]pub fn duplicate_to_stderr(self, dup: Duplicate) -> Self
[src]
Makes the logger write messages with the specified minimum severity additionally to stderr.
Works with all log targets except StdErr
and StdOut
.
#[must_use]pub fn duplicate_to_stdout(self, dup: Duplicate) -> Self
[src]
Makes the logger write messages with the specified minimum severity additionally to stdout.
Works with all log targets except StdErr
and StdOut
.
pub fn format(self, format: FormatFunction) -> Self
[src]
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( write: &mut dyn std::io::Write, now: &mut DeferredNow, record: &Record, ) -> Result<(), std::io::Error>
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.
pub fn format_for_files(self, format: FormatFunction) -> Self
[src]
Makes the logger use the provided format function for messages that are written to files.
Regarding the default, see Logger::format
.
#[must_use]pub fn adaptive_format_for_stderr(self, adaptive_format: AdaptiveFormat) -> Self
[src]
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
.
Only available with feature colors
.
#[must_use]pub fn adaptive_format_for_stdout(self, adaptive_format: AdaptiveFormat) -> Self
[src]
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
.
Only available with feature colors
.
pub fn format_for_stderr(self, format: FormatFunction) -> Self
[src]
Makes the logger use the provided format function for messages that are written to stderr.
Regarding the default, see Logger::format
.
pub fn format_for_stdout(self, format: FormatFunction) -> Self
[src]
Makes the logger use the provided format function to format messages that are written to stdout.
Regarding the default, see Logger::format
.
pub fn format_for_writer(self, format: FormatFunction) -> Self
[src]
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
.
#[must_use]pub fn set_palette(self, palette: String) -> Self
[src]
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.
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
.
Only available with feature colors
.
pub fn directory<S: Into<PathBuf>>(self, directory: S) -> Self
[src]
Specifies a folder for the log files.
This parameter only has an effect if log_to_file()
is used, too.
The specified folder will be created if it does not exist.
By default, the log files are created in the folder where the program was started.
pub fn suffix<S: Into<String>>(self, suffix: S) -> Self
[src]
Specifies a suffix for the log files.
This parameter only has an effect if log_to_file()
is used, too.
#[must_use]pub fn suppress_timestamp(self) -> Self
[src]
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,
and is ignored if rotation is used.
#[must_use]pub fn cleanup_in_background_thread(self, use_background_thread: bool) -> Self
[src]
When rotation is used with some Cleanup
variant, then this option defines
if the cleanup activities (finding files, deleting files, evtl compressing files) is done
in the current thread (in the current log-call), or whether cleanup is delegated to a
background thread.
As of flexi_logger
version 0.14.7
,
the cleanup activities are done by default in a background thread.
This minimizes the blocking impact to your application caused by IO operations.
In earlier versions of flexi_logger
, or if you call this method with
use_background_thread = false
,
the cleanup is done in the thread that is currently causing a file rotation.
#[must_use]pub fn rotate(
self,
criterion: Criterion,
naming: Naming,
cleanup: Cleanup
) -> Self
[src]
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
- 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
rotate_over_size
is given in bytes, e.g. 10_000_000
will rotate
files once they reach a size of 10 MiB.
cleanup
defines the strategy for dealing with older files.
See Cleanup for details.
#[must_use]pub fn append(self) -> Self
[src]
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.
pub fn discriminant<S: Into<String>>(self, discriminant: S) -> Self
[src]
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.
pub fn basename<S: Into<String>>(self, basename: S) -> Self
[src]
The specified String is used as the basename of the log file name, instead of the program name.
This option only has an effect if log_to_file()
is used, too.
pub fn create_symlink<P: Into<PathBuf>>(self, symlink: P) -> Self
[src]
The specified path will be used on linux 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 log_to_file()
is used, too.
Example
You can use the symbolic link to follow the log output with tail
,
even if the log files are rotated.
Assuming the link has the name link_to_log_file
, then use:
tail --follow=name --max-unchanged-stats=1 --retry link_to_log_file
pub fn add_writer<S: Into<String>>(
self,
target_name: S,
writer: Box<dyn LogWriter>
) -> Self
[src]
self,
target_name: S,
writer: Box<dyn LogWriter>
) -> Self
Registers a LogWriter
implementation under the given target name.
The target name must not start with an underscore.
See module writers
.
#[must_use]pub fn use_buffering(self, buffer: bool) -> Self
[src]
Define if buffering should be used.
By default, every log line is directly written to the output, without buffering. This allows seeing new log lines in real time.
Using buffering reduces the program’s I/O overhead, and thus increases overall performance, which can be important if logging is used heavily. On the other hand, if logging is used with low frequency, the log lines can become visible in the output file with significant deferral.
Note that with buffering you should keep the LoggerHandle
and call shutdown
at the very end of your program
to ensure that all buffered log lines are flushed before the program terminates.
#[must_use]pub fn buffer_and_flush(self) -> Self
[src]
Activates buffering (like with Logger::use_buffering
)
and flushes all buffers automatically every second.
Note that flushing uses an extra thread (with minimal stack).
#[must_use]pub fn buffer_and_flush_with(self, capacity: usize, wait: Duration) -> Self
[src]
Activates buffering and flushing (like with Logger::buffer_and_flush
,
but with user-defined buffer capacity and flush frequency.
Note that flushing uses an extra thread (with minimal stack).
#[must_use]pub fn use_windows_line_ending(self) -> Self
[src]
Use Windows line endings, rather than just \n
.
impl Logger
[src]
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
.
#[must_use]pub fn o_print_message(self, print_message: bool) -> Self
[src]
With true, makes the logger print an info message to stdout, each time when a new file is used for log-output.
pub fn o_directory<P: Into<PathBuf>>(self, directory: Option<P>) -> Self
[src]
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.
#[must_use]pub fn o_rotate(
self,
rotate_config: Option<(Criterion, Naming, Cleanup)>
) -> Self
[src]
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.
#[must_use]pub fn o_timestamp(self, timestamp: bool) -> Self
[src]
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.
#[must_use]pub fn o_append(self, append: bool) -> Self
[src]
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.
pub fn o_discriminant<S: Into<String>>(self, discriminant: Option<S>) -> Self
[src]
This option only has an effect if log_to_file
is set to true.
The specified String is added to the log file name.
pub fn o_basename<S: Into<String>>(self, basename: Option<S>) -> Self
[src]
This option only has an effect if log_to_file
is set to true.
The specified String is used as the basename of the log file,
instead of the program name, which is used when None
is given.
pub fn o_create_symlink<P: Into<PathBuf>>(self, symlink: Option<P>) -> Self
[src]
This option only has an effect if log_to_file
is set to true.
If a String is specified, it will be used on linux systems to create in the current folder a symbolic link with this name to the current log file.
impl Logger
[src]
Finally, start logging, optionally with a spec-file.
pub fn start(self) -> Result<LoggerHandle, FlexiLoggerError>
[src]
Consumes the Logger object and initializes flexi_logger
.
The returned reconfiguration handle allows updating the log specification programmatically
later on, e.g. to intensify logging for (buggy) parts of a (test) program, etc.
See LoggerHandle
for an example.
Errors
Several variants of FlexiLoggerError
can occur.
pub fn build(self) -> Result<(Box<dyn Log>, LoggerHandle), FlexiLoggerError>
[src]
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.
The reconfiguration handle allows updating the log specification programmatically
later on, e.g. to intensify logging for (buggy) parts of a (test) program, etc.
See LoggerHandle
for an example.
Errors
Several variants of FlexiLoggerError
can occur.
Auto Trait Implementations
impl !RefUnwindSafe for Logger
impl Send for Logger
impl Sync for Logger
impl Unpin for Logger
impl !UnwindSafe for Logger
Blanket Implementations
impl<T> Any for T where
T: 'static + ?Sized,
[src]
T: 'static + ?Sized,
impl<T> Borrow<T> for T where
T: ?Sized,
[src]
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]
T: ?Sized,
pub fn borrow_mut(&mut self) -> &mut T
[src]
impl<T> From<T> for T
[src]
impl<T, U> Into<U> for T where
U: From<T>,
[src]
U: From<T>,
impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]
U: Into<T>,
type Error = Infallible
The type returned in the event of a conversion error.
pub fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]
impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]
U: TryFrom<T>,