### init() - Quick Start Logger Initialization Source: https://docs.rs/flexi_logger/latest/flexi_logger/fn.init.html The `init()` function is the shortest way to get started with flexi_logger. It configures logging based on the `RUST_LOG` environment variable or defaults to 'info' level, and directs logs to stderr. ```APIDOC ## init() ### Description Provides the shortest form to get started with flexi_logger. It configures logging based on the `RUST_LOG` environment variable or defaults to 'info' level, and directs logs to stderr. ### Method `pub fn init()` ### Endpoint N/A (This is a function call, not an HTTP endpoint) ### Parameters None ### Request Body None ### Request Example ```rust flexi_logger::init(); ``` ### Response None (This function initiates logging and does not return a value directly related to logging output). ### Equivalent Configuration ```rust Logger::try_with_env_or_str("info") .unwrap_or_else(|_e| Logger::with(LogSpecification::info())) .log_to_stderr() .start() .ok(); ``` ### Notes - Log specification can be configured via the environment variable `RUST_LOG`. - If `RUST_LOG` is not set, the default log specification is `'info'`. - Logs are written directly to `stderr` without buffering. - The `LogHandle` returned by `Logger::start()` is implicitly dropped, which is acceptable for this configuration. ``` -------------------------------- ### Example: Keep Log and Compressed Files Source: https://docs.rs/flexi_logger/latest/flexi_logger/enum.Cleanup.html This example demonstrates keeping the youngest five log files as text files and the next 30 as compressed files with a `.gz` suffix. Older files are removed. This variant is available when the `compress` crate feature is enabled. ```rust KeepLogAndCompressedFiles(5,30) ``` -------------------------------- ### Record Example Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.Record.html An example demonstrating how to implement the `log::Log` trait using the `Record` struct to display log messages. ```APIDOC ## Example ```rust struct SimpleLogger; impl log::Log for SimpleLogger { fn enabled(&self, _metadata: &log::Metadata) -> bool { true } fn log(&self, record: &log::Record) { if !self.enabled(record.metadata()) { return; } println!("{}:{} -- {}", record.level(), record.target(), record.args()); } fn flush(&self) {} } ``` ``` -------------------------------- ### Logger Initialization API Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.Logger.html This section covers the primary methods for starting and initializing the FlexiLogger. ```APIDOC ## POST /api/users ### Description Consumes the Logger object and initializes `flexi_logger`. It's crucial to keep the `LoggerHandle` alive until the program terminates to ensure proper flushing and shutdown of log writers. ### Method POST ### Endpoint /start ### Parameters #### Query Parameters - **specfile** (string) - Optional - Path to a specfile for dynamic log specification updates. ### Request Body This method does not explicitly define a request body in the provided documentation. Configuration is typically done via builder methods before calling `start`. ### Response #### Success Response (200) - **LoggerHandle** (object) - A handle to the logger, which must be kept alive. #### Error Response (FlexiLoggerError) - **FlexiLoggerError** (enum) - Various error types that can occur during logger initialization. ### Request Example ```rust use flexi_logger::{Logger, WriteMode, FileSpec}; fn main() -> Result<(), Box> { let _logger = Logger::try_with_str("info")? .log_to_file(FileSpec::default()) .write_mode(WriteMode::BufferAndFlush) .start()?; // ... program logic ... Ok(()) } ``` ``` ```APIDOC ## POST /api/users ### Description Builds a boxed logger and a `LoggerHandle` without initializing the global logger. The returned logger can be installed manually or nested. ### Method POST ### Endpoint /build ### Parameters #### Query Parameters - **specfile** (string) - Optional - Path to a specfile for dynamic log specification updates. ### Request Body This method does not explicitly define a request body. Configuration is typically done via builder methods before calling `build`. ### Response #### Success Response (200) - **(Box, LoggerHandle)** - A tuple containing the boxed logger and a logger handle. #### Error Response (FlexiLoggerError) - **FlexiLoggerError** (enum) - Various error types that can occur during logger building. ### Request Example ```rust use flexi_logger::Logger; fn main() -> Result<(), Box> { let (logger, _handle) = Logger::try_with_str("info")?.build()?; // Use the logger manually or nest it Ok(()) } ``` ``` ```APIDOC ## POST /api/users ### Description Initializes `flexi_logger` using a specfile, allowing the log specification to be updated programmatically while the program is running. If the specfile does not exist, it will be created with the initial specification. ### Method POST ### Endpoint /start_with_specfile ### Parameters #### Path Parameters - **specfile** (string) - Required - The path to the log specification file (e.g., `logspecification.toml`). ### Request Body This method does not explicitly define a request body. Configuration is typically done via builder methods before calling `start_with_specfile`. ### Response #### Success Response (200) - **LoggerHandle** (object) - A handle to the logger, which must be kept alive. #### Error Response (FlexiLoggerError) - **FlexiLoggerError** (enum) - Various error types that can occur during logger initialization. ### Request Example ```rust use flexi_logger::Logger; fn main() -> Result<(), Box> { let _logger = Logger::try_with_str("info")? .start_with_specfile("logspecification.toml")?; // ... program logic ... Ok(()) } ``` ### Specfile Example (`logspecification.toml`) ```toml ### 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' ``` ``` ```APIDOC ## POST /api/users ### Description Builds a boxed logger and a `LoggerHandle` using a specfile, without initializing the global logger. This allows for manual installation or nesting of the logger. ### Method POST ### Endpoint /build_with_specfile ### Parameters #### Path Parameters - **specfile** (string) - Required - The path to the log specification file (e.g., `logspecification.toml`). ### Request Body This method does not explicitly define a request body. Configuration is typically done via builder methods before calling `build_with_specfile`. ### Response #### Success Response (200) - **(Box, LoggerHandle)** - A tuple containing the boxed logger and a logger handle. #### Error Response (FlexiLoggerError) - **FlexiLoggerError** (enum) - Various error types that can occur during logger building. ### Request Example ```rust use flexi_logger::Logger; fn main() -> Result<(), Box> { let (logger, _handle) = Logger::try_with_str("info")?.build_with_specfile("logspecification.toml")?; // Use the logger manually or nest it Ok(()) } ``` ``` -------------------------------- ### Example: Tail Log File via Symlink Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.Logger.html Demonstrates how to use `tail` with a symbolic link to monitor log files, even after rotation. ```bash tail --follow=name --max-unchanged-stats=1 --retry link_to_log_file ``` -------------------------------- ### Initialize flexi_logger with default settings Source: https://docs.rs/flexi_logger/latest/flexi_logger/fn.init.html Use this function for the shortest way to get started with logging. It configures the log specification via the RUST_LOG environment variable or defaults to 'info', and logs directly to stderr. ```rust flexi_logger::init(); ``` ```rust Logger::try_with_env_or_str("info") .unwrap_or_else(|_e| Logger::with(LogSpecification::info())) .log_to_stderr() .start() .ok(); ``` -------------------------------- ### Basic Logger Initialization Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.LoggerHandle.html Demonstrates starting the logger with a simple log level. The LoggerHandle can be ignored if no file or special writer is used. ```rust use flexi_logger::Logger; use std::error::Error; fn main() -> Result<(), Box> { Logger::try_with_str("info")?.start()?; // do work Ok(()) } ``` -------------------------------- ### LoggerHandle Examples Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.LoggerHandle.html Illustrates how to use the LoggerHandle in different scenarios, including basic usage, file logging, and temporary log specification changes. ```APIDOC ## LoggerHandle Examples ### Basic Usage (Ignoring Handle) In more trivial configurations, dropping the `LoggerHandle` has no effect and then you can safely ignore the return value of `Logger::start()`: ```rust use flexi_logger::Logger; use std::error::Error; fn main() -> Result<(), Box> { Logger::try_with_str("info")?.start()?; // do work Ok(()) } ``` ### File Logging (Keeping Handle Alive) When logging to a file or another writer, and/or if you use a buffering or asynchronous `WriteMode`, keep the `LoggerHandle` alive until the program ends: ```rust use flexi_logger::{FileSpec, Logger}; use std::error::Error; fn main() -> Result<(), Box> { let _logger = Logger::try_with_str("info")? .log_to_file(FileSpec::default()) .start()?; // do work Ok(()) } ``` ### Permanent Log Specification Change You can use the logger handle to permanently exchange the log specification programmatically, anywhere in your code: ```rust let logger = Logger::try_with_str("info")?.start()?; // ... logger.parse_new_spec("warn"); // ... ``` ### Temporary Log Specification Change However, when debugging, you might want to modify the log spec only temporarily, for one or few method calls only; this is easier done with the following method, because it allows switching back to the previous spec: ```rust let mut logger = Logger::try_with_str("info")?.start()?; logger.parse_and_push_temp_spec("trace"); // ... // critical calls // ... logger.pop_temp_spec(); // Continue with the log spec you had before. // ... ``` ``` -------------------------------- ### Logger Initialization with File Logging Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.LoggerHandle.html Shows how to start the logger and direct output to a file. The LoggerHandle must be kept alive to ensure proper file handling and logger shutdown. ```rust use flexi_logger::{FileSpec, Logger}; use std::error::Error; fn main() -> Result<(), Box> { let _logger = Logger::try_with_str("info")? .log_to_file(FileSpec::default()) .start()?; // do work Ok(()) } ``` -------------------------------- ### Example Usage of LogfileSelector Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.LogfileSelector.html Demonstrates how to use LogfileSelector with LoggerHandle::existing_log_files to select specific log files, including the current and compressed files. ```rust let all_log_files = logger_handle.existing_log_files( &LogfileSelector::default() .with_r_current() .with_compressed_files() ); ``` -------------------------------- ### Start Logging with a Specification File Source: https://docs.rs/flexi_logger/latest/flexi_logger/code_examples/index.html Initializes the logger using a configuration defined in an external TOML file. This allows for dynamic reconfiguration by editing the file while the program runs. ```rust Logger::try_with_str("info").unwrap() // ... logger configuration ... .start_with_specfile("./server/config/logspec.toml") .unwrap(); ``` -------------------------------- ### FileSpec Default Configuration Example Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.FileSpec.html Demonstrates creating a FileSpec with a custom directory, basename, suppressed timestamp, and suffix, then comparing it to a FileSpec derived from a path string. Ensure the path does not exist as a directory. ```rust assert_eq!( FileSpec::default() .directory("/a/b/c") .basename("foo") .suppress_timestamp() .suffix("bar"), FileSpec::try_from("/a/b/c/foo.bar").unwrap() ); ``` -------------------------------- ### Module trc - Setup Tracing Integration Source: https://docs.rs/flexi_logger/latest/flexi_logger/trc/index.html This section details how to use flexi_logger functionality with the 'tracing' library. It includes functions for setting up tracing and subscribing to specification file changes. ```APIDOC ## Module trc ### Description Use `flexi_logger` functionality with `tracing`. `tracing` is an alternative to `log`. It has a similar base architecture, but is optimized for supporting async apps, which adds complexity due to the need to manage contexts. `tracing-subscriber` facilitates contributing “backends”, and is used by `setup_tracing` to plug `flexi_logger`-functionality into `tracing`. ### Structs #### FormatConfig Configuration for the `tracing` formatting. #### SpecFileNotifier Rereads the specfile if it was updated and forwards the update to `tracing`’s filter. ### Traits #### LogSpecSubscriber Trait that allows to register for changes to the log specification. ### Functions #### setup_tracing Set up tracing to write into the specified `FileLogWriter`, and to use the (optionally) specified specfile. #### subscribe_to_specfile Allows registering a `LogSpecSubscriber` to a specfile. ### Request Example ```json { "specfile": "/path/to/specfile.toml" } ``` ### Response Example ```json { "status": "success", "message": "Tracing setup complete." } ``` ``` -------------------------------- ### Configure Default Log File Behavior Source: https://docs.rs/flexi_logger/latest/flexi_logger/code_examples/index.html Sets default formatting for stderr, stdout, and files. This example shows the equivalent of FlexiLogger's default initialization. ```rust // ... .adaptive_format_for_stderr(AdaptiveFormat::Default) .adaptive_format_for_stdout(AdaptiveFormat::Default) .format_for_files(default_format) .format_for_writer(default_format) ``` -------------------------------- ### Initialize Logger from Environment Variable Source: https://docs.rs/flexi_logger/latest/flexi_logger/index.html Use this to initialize the logger with settings read from an environment variable and direct output to stderr. Ensure the `Logger` and `start` methods are available. ```rust flexi_logger::Logger::try_with_env().unwrap().start().unwrap(); ``` -------------------------------- ### Timestamps Custom Format Example Source: https://docs.rs/flexi_logger/latest/flexi_logger/enum.Naming.html Illustrates the TimestampsCustomFormat variant with a specific current infix and timestamp format. This is equivalent to the Timestamps variant. ```rust Naming::TimestampsCustomFormat { current_infix: Some("rCURRENT"), format: "r%Y-%m-%d_%H-%M-%S", } ``` -------------------------------- ### Start Flexi Logger with File Logging Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.Logger.html Initializes flexi_logger with a specified log level and directs output to a file. Ensure the LoggerHandle is kept alive until program termination to prevent premature shutdown of writers. ```rust use flexi_logger::{Logger,WriteMode, FileSpec}; fn main() -> Result<(), Box> { 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(()) } ``` -------------------------------- ### Setup Tracing with FileLogWriter and Specfile Source: https://docs.rs/flexi_logger/latest/flexi_logger/trc/fn.setup_tracing.html Use FileLogWriter as a trace writer with support for dynamically adapting trace levels. The FileLogWriter's formatting is bypassed in favor of tracing's formatting, configurable via FormatConfig. Ensure the returned handles are kept alive until program shutdown. ```rust use std::{error::Error, path::PathBuf}; use flexi_logger::{ trc::FormatConfig, writers::FileLogWriter, Age, Cleanup, Criterion, FileSpec, LogSpecification, Naming, WriteMode, }; // Drop the keep-alive-handles only in the shutdown of your program let _keep_alive_handles = flexi_logger::trc::setup_tracing( LogSpecification::info(), Some(&PathBuf::from("trcspecfile.toml")), FileLogWriter::builder(FileSpec::default()) .rotate( Criterion::Age(Age::Day), Naming::Timestamps, Cleanup::KeepLogFiles(7), ) .write_mode(WriteMode::Async), &FormatConfig::default() .with_file(true), )?; tracing::debug!("now we start doing what we really wanted to do..."); ``` -------------------------------- ### Define a Simple Logger with flexi_logger Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.Record.html Implement the `log::Log` trait to create a custom logger. This example shows how to process and display log records. ```rust struct SimpleLogger; impl log::Log for SimpleLogger { fn enabled(&self, _metadata: &log::Metadata) -> bool { true } fn log(&self, record: &log::Record) { if !self.enabled(record.metadata()) { return; } println!("{}:{} -- {}", record.level(), record.target(), record.args()); } fn flush(&self) {} } ``` -------------------------------- ### Configure Log File Location and Naming Source: https://docs.rs/flexi_logger/latest/flexi_logger/code_examples/index.html Specify a directory, basename, discriminant, and suffix for log files. This example also enables printing a message to stdout indicating the log file location and creates a symbolic link on Unix-like systems. ```rust Logger::try_with_str("info")? .log_to_file( FileSpec::default() .directory("log_files") // create files in folder ./log_files .basename("foo") .discriminant("Sample4711A") // use infix in log file name .suffix("trc") // use suffix .trc instead of .log ) .print_message() // .create_symlink("current_run") // create a symbolic link to the current log file .start()?; ``` -------------------------------- ### Initialize Logger with Spec File Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.Logger.html Starts flexi_logger using a configuration file for log specifications. The logger will create the spec file if it doesn't exist. The LoggerHandle must be kept alive for the spec file to be dynamically updated. ```rust use flexi_logger::Logger; Logger::try_with_str("info") .unwrap() // more logger configuration .start_with_specfile("logspecification.toml"); ``` -------------------------------- ### Example Log Specification File Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.Logger.html This TOML file defines logging levels and patterns for flexi_logger. It supports a global level, an optional global pattern, and specific levels for different modules. ```toml ### 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' ``` -------------------------------- ### Get Configured Suffix Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.FileLogWriterConfig.html Retrieves the configured suffix for the log file name. Returns an Option. ```rust pub fn suffix(&self) -> Option ``` -------------------------------- ### Example Log File Naming with Rotation Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.FileLogWriterBuilder.html Illustrates the file naming convention when rotation is enabled with `Naming::Numbers`. Log files will have an infix like `_rCURRENT` and be renamed sequentially upon rotation. ```text my_prog_r00000.log my_prog_r00001.log my_prog_r00002.log my_prog_rCURRENT.log ``` -------------------------------- ### Configure and Use Custom Log Writers in Rust Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/index.html This example demonstrates how to configure a `FileLogWriter` for alert messages and use it alongside the default logger. It also shows how to define a macro to simplify sending logs to multiple targets, including the custom 'Alert' target and the default output. ```rust use log::*; use flexi_logger::{FileSpec,Logger}; use flexi_logger::writers::FileLogWriter; // Configure a FileLogWriter for alert messages pub fn alert_logger() -> Box { Box::new(FileLogWriter::builder( FileSpec::default() .discriminant("Alert") .suffix("alerts") ) .print_message() .try_build() .unwrap()) } // Define a macro for writing messages to the alert log and to the normal log #[macro_use] mod macros { #[macro_export] macro_rules! alert_error { ($($arg:tt)*) => ( error!(target: "{Alert,_Default}", $($arg)*); ) } } fn main() { Logger::try_with_env_or_str("info") .expect("LogSpecification String has errors") .print_message() .log_to_file(FileSpec::default()) .add_writer("Alert", alert_logger()) .start() .unwrap_or_else(|e| panic!("Logger initialization failed with {}", e)); // Explicitly send logs to different loggers error!(target : "{Alert}", "This is only an alert"); error!(target : "{Alert,_Default}", "This is an alert and log message"); // Nicer: use the explicit macro alert_error!("This is another alert and log message"); // Standard log macros write only to the normal log error!("This is a normal error message"); warn!("This is a warning"); info!("This is an info message"); debug!("This is a debug message - you will not see it"); trace!("This is a trace message - you will not see it"); } ``` -------------------------------- ### flexi_logger Format Error Example Source: https://docs.rs/flexi_logger/latest/flexi_logger/error_info/index.html Indicates an error produced by the chosen log format function. If this occurs with provided format functions, consider opening an issue. ```rust [flexi_logger][ERRCODE::Format] formatting failed, caused by ... ``` -------------------------------- ### TimestampsDirect Custom Format Example Source: https://docs.rs/flexi_logger/latest/flexi_logger/enum.Naming.html Illustrates the TimestampsCustomFormat variant with no specific current infix and a timestamp format. This is equivalent to the TimestampsDirect variant. ```rust Naming::TimestampsCustomFormat { current_infix: None, format: "r%Y-%m-%d_%H-%M-%S", } ``` -------------------------------- ### Log to File and Duplicate to Stderr Source: https://docs.rs/flexi_logger/latest/flexi_logger/code_examples/index.html Configure the logger to write logs to a file and also duplicate warnings and errors to stderr. This example uses a default file specification and the Duplicate::Warn setting. ```rust Logger::try_with_str("info")? .log_to_file(FileSpec::default()) // write logs to file .duplicate_to_stderr(Duplicate::Warn) // print warnings and errors also to the console .start()?; ``` -------------------------------- ### Implement Stateful Log Filtering with LogLineFilter Source: https://docs.rs/flexi_logger/latest/flexi_logger/filter/index.html Demonstrates how to create a custom log filter that only allows log lines containing the word 'bar'. This example requires the `flexi_logger` and `log` crates. The filter is applied using `Logger::filter` after initialization. ```rust use flexi_logger::{ filter::{LogLineFilter, LogLineWriter}, DeferredNow, FlexiLoggerError, }; pub struct BarsOnly; impl LogLineFilter for BarsOnly { fn write( &self, now: &mut DeferredNow, record: &log::Record, log_line_writer: &dyn LogLineWriter, ) -> std::io::Result<()> { if record.args().to_string().contains("bar") { log_line_writer.write(now, record)?; } Ok(()) } } fn main() -> Result<(), FlexiLoggerError> { flexi_logger::Logger::try_with_str("info")? .filter(Box::new(BarsOnly)) .start()?; log::info!("barista"); log::info!("foo"); // will be swallowed by the filter log::info!("bar"); log::info!("gaga"); // will be swallowed by the filter Ok(()) } ``` -------------------------------- ### Check if Message is Printed on Program Start Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.FileLogWriterConfig.html Checks if a message indicating the log file path should be printed when the program starts. Returns true if the message is to be printed. ```rust pub fn print_message(&self) -> bool ``` -------------------------------- ### setup_tracing Function Source: https://docs.rs/flexi_logger/latest/flexi_logger/trc/fn.setup_tracing.html Sets up tracing to write into a specified `FileLogWriter` and optionally use a specfile for dynamic log level adaptation. Note that the `FileLogWriter`'s formatting is bypassed in favor of `tracing`'s formatting, configurable via `FormatConfig`. ```APIDOC ## setup_tracing ### Description Sets up tracing to write into the specified `FileLogWriter`, and to use the (optionally) specified specfile. The `FileLogWriter`’s formatting are bypassed and not be used, instead the `tracing` formatting will be used, which can be configured via `config: FormatConfig`. ### Method `pub fn setup_tracing` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **initial_logspec** (LogSpecification) - Required - The initial log specification. - **o_specfile** (Option<&PathBuf>) - Optional - An optional path to a specification file. - **flwb** (FileLogWriterBuilder) - Required - The builder for the file log writer. - **config** (&FormatConfig) - Required - The format configuration for tracing. ### Returns - Result<(FileLogWriterHandle, SpecFileNotifier), FlexiLoggerError> - A tuple containing the file log writer handle and the spec file notifier, or a `FlexiLoggerError`. ### Example ```rust use std::{error::Error, path::PathBuf}; use flexi_logger::{ trc::FormatConfig, writers::FileLogWriter, Age, Cleanup, Criterion, FileSpec, LogSpecification, Naming, WriteMode, }; // Drop the keep-alive-handles only in the shutdown of your program let _keep_alive_handles = flexi_logger::trc::setup_tracing( LogSpecification::info(), Some(&PathBuf::from("trcspecfile.toml")), FileLogWriter::builder(FileSpec::default()) .rotate( Criterion::Age(Age::Day), Naming::Timestamps, Cleanup::KeepLogFiles(7), ) .write_mode(WriteMode::Async), &FormatConfig::default() .with_file(true), )?; tracing::debug!("now we start doing what we really wanted to do..."); ``` ### Errors Various variants of `FlexiLoggerError` can occur. ``` -------------------------------- ### Get Type ID Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.FileLogWriterBuilder.html Retrieves the `TypeId` of the current object. This is part of the `Any` trait implementation. ```rust type_id(&self) -> TypeId ``` -------------------------------- ### Initialize File Logging with Base Configuration Source: https://docs.rs/flexi_logger/latest/flexi_logger/code_examples/index.html Sets up logging to files with a specified base name and directory. The `log` crate and `flexi_logger` must be imported. ```rust use flexi_logger::{writers::FileLogWriter, Cleanup, Criterion, FileSpec, Naming}; let logger = flexi_logger::Logger::try_with_str("info")? .log_to_file( FileSpec::default() .basename("phase1") .directory("./log_files") ) .start()?; log::info!("start of phase 1"); ``` -------------------------------- ### Build and Apply Log Specification Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.LogSpecBuilder.html Demonstrates how to build an initial log specification, initialize the logger, and then modify and reapply the specification using LogSpecBuilder. ```rust use flexi_logger::{Logger, LogSpecification}; use log::LevelFilter; fn main() { // Build the initial log specification let mut builder = LogSpecification::builder(); builder .default(LevelFilter::Info) .module("karl", LevelFilter::Debug); // Initialize Logger, keep builder alive let mut logger = Logger::with(builder.build()) // your logger configuration goes here, as usual .start() .unwrap_or_else(|e| panic!("Logger initialization failed with {}", e)); // ... // Modify builder and update the logger builder .default(LevelFilter::Error) .remove("karl") .module("emma", LevelFilter::Trace); logger.set_new_spec(builder.build()); // ... } ``` -------------------------------- ### Programmatically Change Log Specification Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.LoggerHandle.html Illustrates how to permanently update the logger's specification string after it has been started. ```rust let logger = Logger::try_with_str("info")?.start()?; // ... logger.parse_new_spec("warn"); // ... ``` -------------------------------- ### LogWriter max_log_level Method Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/trait.LogWriter.html Provided method to get the maximum log level to be written. Defaults to `LevelFilter`. ```rust fn max_log_level(&self) -> LevelFilter { ... } ``` -------------------------------- ### Get Configured Directory Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.FileLogWriterConfig.html Retrieves the configured directory path for the FileLogWriter. This method returns a reference to the Path object. ```rust pub fn directory(&self) -> &Path ``` -------------------------------- ### Get Configured Discriminant Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.FileLogWriterConfig.html Retrieves the configured discriminant, which can be used for unique log file identification. Returns an Option. ```rust pub fn discriminant(&self) -> Option ``` -------------------------------- ### LogSpecBuilder - Initialization Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.LogSpecBuilder.html Demonstrates how to create a new LogSpecBuilder and configure initial logging levels. ```APIDOC ## LogSpecBuilder - Initialization ### Description Initializes a `LogSpecBuilder` and sets default and module-specific log level filters. ### Methods - `LogSpecification::builder()`: Creates a new `LogSpecBuilder`. - `default(LevelFilter)`: Sets the default log level filter. - `module(module_name, LevelFilter)`: Sets the log level filter for a specific module. ### Request Example ```rust use flexi_logger::{LogSpecification, Logger}; use log::LevelFilter; let mut builder = LogSpecification::builder(); builder .default(LevelFilter::Info) .module("karl", LevelFilter::Debug); let logger = Logger::with(builder.build()).start().unwrap(); ``` ``` -------------------------------- ### Get Configured Basename Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.FileLogWriterConfig.html Retrieves the configured basename for the log file. This is the base name used for log file naming. ```rust pub fn basename(&self) -> &str ``` -------------------------------- ### Get Current Log Specification Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.LoggerHandle.html Obtains a copy of the current log specification. This operation can fail if the internal mutex is poisoned. ```rust let spec = logger.current_log_spec()?; ``` -------------------------------- ### Check if Appending to Existing Files Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.FileLogWriterConfig.html Determines if existing log files should be appended to when the program starts. Returns true if appending is enabled. ```rust pub fn append(&self) -> bool ``` -------------------------------- ### Get FileLogWriter Configuration Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.FileLogWriter.html Retrieves the current configuration of the FileLogWriter. This can be useful for inspection or for providing configuration details to other methods like `reset`. ```rust pub fn config(&self) -> Result ``` -------------------------------- ### Get Style for Log Level Source: https://docs.rs/flexi_logger/latest/flexi_logger/fn.style.html Helper function to apply colors based on log level. Requires the 'colors' crate feature. ```rust pub fn style(level: Level) -> Style ``` -------------------------------- ### Logger Initialization and Configuration Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.Logger.html Methods for creating and configuring the Logger instance, including setting log level specifications and output destinations. ```APIDOC ## Logger Configuration ### `Logger::with(logspec)` Creates a Logger with an explicit `LogSpecification`. #### Parameters - `logspec` (impl Into) - The log specification to use. #### Examples ```rust use log::LevelFilter; use flexi_logger::Logger; let logger = Logger::with(LevelFilter::Info).start().unwrap(); ``` ```rust use flexi_logger::{Logger, LogSpecification}; let logger = Logger::with( LogSpecification::parse("info, critical_mod = trace").unwrap() ).start().unwrap(); ``` ### `Logger::try_with_str(s)` Creates a Logger that reads the `LogSpecification` from a String or &str. #### Parameters - `s` (S: AsRef) - The string containing the log specification. #### Errors - `FlexiLoggerError::Parse` if the String uses an erroneous syntax. ### `Logger::try_with_env()` Creates a Logger that reads the `LogSpecification` from the environment variable `RUST_LOG`. #### Errors - `FlexiLoggerError::Parse` if the value of `RUST_LOG` is malformed. ### `Logger::try_with_env_or_str(s)` 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. #### Parameters - `s` (S: AsRef) - The string to use if `RUST_LOG` is not set. #### Errors - `FlexiLoggerError::Parse` if the chosen value is malformed. ### Output Destinations #### `log_to_stderr(self)` Log is written to stderr (which is the default). #### `log_to_stdout(self)` Log is written to stdout. #### `log_to_file(self, file_spec)` Log is written to a file. See `FileSpec` for details about the filename pattern. #### `log_to_writer(self, w)` Log is written to the provided writer. #### `log_to_file_and_writer(self, file_spec, w)` Log is written to a file and an alternative `LogWriter` implementation. #### `log_to_buffer(self, max_size, format_function)` Available on **crate feature `buffer_writer`** only. Log is written to an in-memory buffer. #### `do_not_log(self)` Log is processed but not written to any destination. #### `print_message(self)` Makes the logger print an info message to stdout with the name of the logfile when a logfile is opened for writing. ``` -------------------------------- ### Register Custom Log Writer Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.Logger.html Registers a custom `LogWriter` implementation under a specified target name. Target names must not start with an underscore. ```rust pub fn add_writer>( self, target_name: S, writer: Box, ) -> Self ``` -------------------------------- ### Get Maximum Log Level Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.FileLogWriter.html Implements the `max_log_level` method for the LogWriter trait, returning the maximum log level that the writer is configured to handle. ```rust fn max_log_level(&self) -> LevelFilter ``` -------------------------------- ### flexi_logger Write Error Example Source: https://docs.rs/flexi_logger/latest/flexi_logger/error_info/index.html Indicates a failure during the writing of a log line to the output. This can occur with asynchronous writers if the logger handle is dropped prematurely. ```rust [flexi_logger][ERRCODE::Write] writing log line failed, caused by Send ``` -------------------------------- ### Configure Log Rotation with Age, Timestamps, and Cleanup Source: https://docs.rs/flexi_logger/latest/flexi_logger/code_examples/index.html Sets up file logging with daily rotation, timestamped filenames for rotated files, and keeps a maximum of 7 log files. Ensure the 'log' crate is a dependency. ```rust Logger::try_with_str("info")? // Write all error, warn, and info messages .log_to_file( FileSpec::default() ) .rotate( Criterion::Age(Age::Day), Naming::Timestamps, Cleanup::KeepLogFiles(7), ) .start()?; ``` -------------------------------- ### Initialize Flexi Logger with Environment or Programmatic String Source: https://docs.rs/flexi_logger/latest/flexi_logger/code_examples/index.html Initialize the logger using both environment variable and a programmatic string, with the environment variable taking precedence. Ensure the log crate is used for logging macros. ```rust Logger::try_with_env_or_str("info")?.start()?; ``` -------------------------------- ### Get FileLogWriter Format Function Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.FileLogWriter.html Retrieves the currently configured output format function for the FileLogWriter. This function determines how log records are formatted before writing. ```rust pub fn format(&self) -> FormatFunction ``` -------------------------------- ### Get Current Maximum Log Level Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.LoggerHandle.html Retrieves the current maximum log level filter applied by the logger. This can fail if the internal mutex is poisoned. ```rust let level = logger.current_max_level()?; ``` -------------------------------- ### Initialize Flexi Logger Programmatically Source: https://docs.rs/flexi_logger/latest/flexi_logger/code_examples/index.html Initialize the logger by providing the log specification string directly. Ensure the log crate is used for logging macros. ```rust Logger::try_with_str("info")?.start()?; ``` -------------------------------- ### Initialize Flexi Logger with Default Settings Source: https://docs.rs/flexi_logger/latest/flexi_logger/code_examples/index.html A shorthand for initializing the logger with default settings, typically writing to stderr. Ensure the log crate is used for logging macros. ```rust flexi_logger::init(); ``` -------------------------------- ### flexi_logger Flush Error Example Source: https://docs.rs/flexi_logger/latest/flexi_logger/error_info/index.html Indicates a failure during explicit or automatic flushing of buffered log lines. Similar reasons to Write errors may apply. ```rust [flexi_logger][ERRCODE::Flush] flushing primary writer failed, caused by Send ``` -------------------------------- ### CloneToUninit for T Source: https://docs.rs/flexi_logger/latest/flexi_logger/enum.Level.html Nightly-only experimental API for cloning to uninitialized memory. ```APIDOC ## CloneToUninit for T ### Description Nightly-only experimental API for cloning to uninitialized memory. ### Method `clone_to_uninit` ### Endpoint N/A (Trait implementation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Get File Log Writer Configuration Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.LoggerHandle.html Retrieves the current configuration of the file log writer. This operation can fail if no file logger is configured or if a mutex is poisoned. ```rust let config = logger.flw_config()?; ``` -------------------------------- ### Initialize Flexi Logger with Environment Variable Source: https://docs.rs/flexi_logger/latest/flexi_logger/code_examples/index.html Initialize the logger using the RUST_LOG environment variable. Ensure the log crate is used for logging macros. ```rust Logger::try_with_env()?.start()?; ``` -------------------------------- ### From Trait Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.ArcFileLogWriter.html Method for creating an instance from another type. ```APIDOC ## fn from(t: T) -> T ### Description Returns the argument unchanged. This is part of the `From for T` implementation. ### Method POST ### Endpoint N/A (Method within a trait) ### Parameters - **t** (T) - Required - The value to convert from. ### Request Example None ### Response #### Success Response (200) - **T** (T) - The converted value. #### Response Example None ``` -------------------------------- ### flexi_logger LogSpecFile Watching Error Example Source: https://docs.rs/flexi_logger/latest/flexi_logger/error_info/index.html Indicates a failure while watching the log specification file. This error occurs when the file's monitoring process encounters an issue. ```rust [flexi_logger][ERRCODE::LogSpecFile] error while watching the specfile, caused by ... ``` -------------------------------- ### Include File Name - FormatConfig Source: https://docs.rs/flexi_logger/latest/flexi_logger/trc/struct.FormatConfig.html Decides whether to include the file name in the output. Defaults to `false`. ```rust pub fn with_file(self, with_file: bool) -> Self ``` -------------------------------- ### Symlink Creation Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.FileLogWriterBuilder.html Configure the creation of a symbolic link to the current log file on Unix systems. ```APIDOC ## POST /websites/rs_flexi_logger_flexi_logger/o_create_symlink ### Description On Unix systems, this option creates a symbolic link in the current directory with the specified name, pointing to the current log file. ### Method POST ### Endpoint /websites/rs_flexi_logger_flexi_logger/o_create_symlink ### Parameters #### Request Body - **symlink** (Option) - Optional - The name of the symbolic link to create. ### Request Example ```json { "symlink": "current_log.log" } ``` ### Response #### Success Response (200) - **Self** (Self) - The updated logger configuration. #### Response Example ```json { "message": "Symlink creation configured successfully" } ``` ``` -------------------------------- ### Get Existing Log Files Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.FileLogWriterHandle.html Retrieves a list of existing log files based on the provided LogfileSelector. This can include the current log file and compressed files if they exist. ```rust pub fn existing_log_files( &self, selector: &LogfileSelector, ) -> Result, FlexiLoggerError> ``` -------------------------------- ### Create Symbolic Link on Unix Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.FileLogWriterBuilder.html On Unix systems, this creates a symbolic link in the current directory pointing to the current log file. ```rust pub fn create_symlink>(self, symlink: P) -> Self ``` -------------------------------- ### Enable Adaptive Coloring for Stderr Source: https://docs.rs/flexi_logger/latest/flexi_logger/code_examples/index.html Conditionally enable colored output for stderr. Colors are used when outputting to a terminal (tty) and suppressed otherwise, for example, when piping to another program. ```rust flexi_logger::Logger::try_with_str("info")? .adaptive_format_for_stderr(AdaptiveFormat::Detailed); ``` -------------------------------- ### FormatConfig Configuration Source: https://docs.rs/flexi_logger/latest/flexi_logger/trc/struct.FormatConfig.html Configuration options for formatting logs when using flexi_logger with the tracing crate. ```APIDOC ## Struct FormatConfig ### Description Configuration for the `tracing` formatting. Exposes the formatting capabilities of `tracing-subscriber::FmtSubscriber`. These deviate from the formatting capabilities of `flexi_logger`. ### Methods #### `with_ansi(self, with_ansi: bool) -> Self` Decides whether to use ANSI colors in the output. Defaults to `false`. #### `with_file(self, with_file: bool) -> Self` Decides whether to include the file name in the output. Defaults to `false`. #### `with_level(self, with_level: bool) -> Self` Decides whether to include the log level in the output. Defaults to `true`. #### `with_line_number(self, with_line_number: bool) -> Self` Decides whether to include the line number in the output. Defaults to `true`. #### `with_target(self, with_target: bool) -> Self` Decides whether to include the target in the output. Defaults to `false`. #### `with_thread_ids(self, with_thread_ids: bool) -> Self` Decides whether to include the thread IDs in the output. Defaults to `false`. #### `with_thread_names(self, with_thread_names: bool) -> Self` Decides whether to include the thread names in the output. Defaults to `false`. #### `with_time(self, with_time: bool) -> Self` Decides whether to include the time in the output. Defaults to `true`. ### Default Implementation #### `default() -> Self` Returns the default value for `FormatConfig`. ``` -------------------------------- ### Configure Symlink Creation Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.Logger.html On Unix systems, creates a symbolic link in the current folder with the specified name, pointing to the current log file. Has no effect on non-Unix systems or if logs are not written to files. ```rust pub fn o_create_symlink>(self, symlink: Option

) -> Self ``` -------------------------------- ### Include Target - FormatConfig Source: https://docs.rs/flexi_logger/latest/flexi_logger/trc/struct.FormatConfig.html Decides whether to include the target in the output. Defaults to `false`. ```rust pub fn with_target(self, with_target: bool) -> Self ``` -------------------------------- ### Build FileLogWriter Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.FileLogWriterBuilder.html Constructs and returns a `FileLogWriter` instance. Returns `FlexiLoggerError::Io` if the specified path is invalid. ```rust pub fn try_build(self) -> Result ``` -------------------------------- ### flexi_logger LogSpecFile Rereading Error Example Source: https://docs.rs/flexi_logger/latest/flexi_logger/error_info/index.html Indicates that rereading the log specification file failed, causing the logger to continue with the previous specification. This can happen if the file cannot be opened, read, or parsed. ```rust [flexi_logger][ERRCODE::LogSpecFile] continuing with previous log specification, because rereading the log specification file failed, caused by ... ``` -------------------------------- ### SyslogConnection Factory Methods Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.SyslogConnection.html Methods for creating SyslogConnection instances, each tailored for different syslog configurations and environments. ```APIDOC ## SyslogConnection Implements the connection to the syslog. Choose one of the factory methods that matches your environment, depending on how the syslog is managed on your system, how you can access it and with which protocol you can write to it. Is required to instantiate a `SyslogWriter`. ### `try_datagram>(path: P) -> IoResult` **Available on `Unix` only.** Returns a `Syslog` that connects via unix datagram to the specified path. **Errors:** Any kind of I/O error can occur. ### `try_stream>(path: P) -> IoResult` **Available on `Unix` only.** Returns a `Syslog` that connects via unix stream to the specified path. **Errors:** Any kind of I/O error can occur. ### `syslog_call() -> Self` **Available on `Unix` only.** Returns a `Syslog` that delegates on the POSIX-standard `syslog` C function provided by the platform’s standard C library to send logs. This is ideal for portably sending logs to whatever system logging service may be available. ### `try_tcp(server: T) -> IoResult` Returns a `Syslog` that sends the log lines via TCP to the specified address. **Errors:** `std::io::Error` if opening the stream fails. ### `try_udp(local: T, server: T) -> IoResult` Returns a `Syslog` that sends the log via the fragile UDP protocol from local to server. **Errors:** `std::io::Error` if opening the stream fails. ``` -------------------------------- ### Conditionally Print Info Message Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.FileLogWriterBuilder.html Controls whether an info message is printed to stdout when a new log file is used. This method allows flexible control, for example, based on command-line arguments. ```rust pub fn o_print_message(self, print_message: bool) -> Self ``` -------------------------------- ### Configure Log File Rotation Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.FileLogWriterBuilder.html Set up log file rotation based on size and cleanup strategy. The size is specified in bytes. A cleanup strategy can limit disk space usage. ```rust o_rotate(self, rotate_config: Option<(Criterion, Naming, Cleanup)>) ``` -------------------------------- ### Create Symbolic Link for Log File Source: https://docs.rs/flexi_logger/latest/flexi_logger/writers/struct.FileLogWriterBuilder.html On Unix-like systems, create a symbolic link with a specified name in the current folder that points to the current log file. This is useful for easily accessing the latest log. ```rust o_create_symlink>(self, symlink: Option) ``` -------------------------------- ### Create Symbolic Link Source: https://docs.rs/flexi_logger/latest/flexi_logger/struct.Logger.html Creates a symbolic link to the current log file on Unix systems. ```APIDOC ## POST /create_symlink ### Description Creates a symbolic link to the current log file on Unix systems. This is useful for following log output with tools like `tail`. ### Method POST ### Endpoint /create_symlink ### Parameters #### Request Body - **symlink** (P: Into) - Required - The path for the symbolic link to be created. ```