[][src]Struct flexi_logger::Logger

pub struct Logger { /* fields omitted */ }

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

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:

This example panics
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.

pub fn log_to_file(self) -> Self[src]

Is equivalent to log_target(LogTarget::File).

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.

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.

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.

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

This example is not tested
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.

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.

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.

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.

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.

pub fn rotate(
    self,
    criterion: Criterion,
    naming: Naming,
    cleanup: Cleanup
) -> Self
[src]

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.

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.

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]

Registers a LogWriter implementation under the given target name.

The target name must not start with an underscore.

See the module documentation of writers.

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.

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.

pub fn o_rotate(
    self,
    rotate_config: Option<(Criterion, Naming, Cleanup)>
) -> Self
[src]

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.

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.

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.

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<ReconfigurationHandle, 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 ReconfigurationHandle for an example.

Errors

Several variants of FlexiLoggerError can occur.

pub fn build(
    self
) -> Result<(Box<dyn Log>, ReconfigurationHandle), FlexiLoggerError>
[src]

Builds a boxed logger and a ReconfigurationHandle 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 ReconfigurationHandle for an example.

Errors

Several variants of FlexiLoggerError can occur.

pub fn start_with_specfile<P: AsRef<Path>>(
    self,
    specfile: P
) -> Result<ReconfigurationHandle, FlexiLoggerError>
[src]

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

This example is not tested
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.

Errors

Several variants of FlexiLoggerError can occur.

Returns

A ReconfigurationHandle is returned, predominantly to allow using its shutdown method.

pub fn build_with_specfile<P: AsRef<Path>>(
    self,
    specfile: P
) -> Result<(Box<dyn Log>, ReconfigurationHandle), FlexiLoggerError>
[src]

Builds a boxed logger and a ReconfigurationHandle 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.

For the properties of the returned logger, see start_with_specfile().

Errors

Several variants of FlexiLoggerError can occur.

Returns

A ReconfigurationHandle is returned, predominantly to allow using its shutdown method.

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]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.