Skip to main content

Logger

Struct Logger 

Source
pub struct Logger { /* private fields */ }
Expand description

A structured logger instance.

Implementations§

Source§

impl Logger

Source

pub fn new() -> Self

Creates a new logger with default settings.

Source

pub fn with_options(opts: Options) -> Self

Creates a new logger with the given options.

Source

pub fn set_level(&self, level: Level)

Sets the minimum log level.

Source

pub fn level(&self) -> Level

Returns the current log level.

Source

pub fn set_prefix(&self, prefix: impl Into<String>)

Sets the log prefix.

Source

pub fn prefix(&self) -> String

Returns the current prefix.

Source

pub fn set_report_timestamp(&self, report: bool)

Sets whether to report timestamps.

Source

pub fn set_report_caller(&self, report: bool)

Sets whether to report caller location.

§Performance Warning

When enabled, this captures a full stack backtrace on every log call, which is approximately 100-1000x slower than normal logging.

ConfigurationTypical LatencyUse Case
Default (no caller)~100 nsProduction
With caller~100 μsDebug only

Only enable during active debugging sessions. Do NOT enable in production.

A runtime warning will be emitted on the first log call with caller reporting enabled (unless suppressed via suppress_caller_warning).

Source

pub fn suppress_caller_warning(&self)

Suppresses the runtime performance warning for caller reporting.

By default, when caller reporting is enabled, a warning is emitted to stderr on the first log call to alert developers about the significant performance overhead (~100-1000x slower).

Call this method to suppress the warning when you have intentionally enabled caller reporting and understand the performance implications.

§Example
use charmed_log::Logger;

let logger = Logger::new();
logger.set_report_caller(true);
logger.suppress_caller_warning();
// No warning will be emitted on first log call
logger.info("debug message", &[]);
Source

pub fn set_time_format(&self, format: impl Into<String>)

Sets the time format.

Source

pub fn set_formatter(&self, formatter: Formatter)

Sets the formatter.

Source

pub fn set_styles(&self, styles: Styles)

Sets the styles.

Source

pub fn with_fields(&self, fields: &[(&str, &str)]) -> Self

Creates a new logger with additional fields.

This is the idiomatic Rust method name. For Go API compatibility, use with instead.

Source

pub fn with(&self, fields: &[(&str, &str)]) -> Self

Creates a new logger with additional fields (Go API compatibility).

This method matches the Go log.With() API. It is equivalent to with_fields.

§Example
use charmed_log::Logger;

let logger = Logger::new();
let ctx_logger = logger.with(&[("request_id", "abc123"), ("user", "alice")]);
ctx_logger.info("Processing request", &[]);
Source

pub fn with_prefix(&self, prefix: impl Into<String>) -> Self

Creates a new logger with a different prefix.

Source

pub fn with_error_handler<F>(self, handler: F) -> Self
where F: Fn(Error) + Send + Sync + 'static,

Sets an error handler for I/O failures during logging.

When writing log output fails (e.g., disk full, pipe closed, permission denied), the handler is called with the I/O error. This allows applications to respond appropriately instead of silently losing log messages.

§Default Behavior

If no error handler is configured:

  • First failure: A warning is printed to stderr (if available)
  • Subsequent failures: Silent (to avoid infinite loops)
§Example
use charmed_log::Logger;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

let error_count = Arc::new(AtomicUsize::new(0));
let counter = error_count.clone();

let logger = Logger::new().with_error_handler(move |err| {
    counter.fetch_add(1, Ordering::Relaxed);
    eprintln!("Log write failed: {}", err);
});
Source

pub fn log(&self, level: Level, msg: &str, keyvals: &[(&str, &str)])

Logs a message at the specified level.

This method uses a single write lock for the entire operation (format + write) to ensure configuration consistency. The only exception is caller info capture, which happens inside formatting but is atomic with respect to the log entry.

Source

pub fn debug(&self, msg: &str, keyvals: &[(&str, &str)])

Logs a debug message.

Source

pub fn info(&self, msg: &str, keyvals: &[(&str, &str)])

Logs an info message.

Source

pub fn warn(&self, msg: &str, keyvals: &[(&str, &str)])

Logs a warning message.

Source

pub fn error(&self, msg: &str, keyvals: &[(&str, &str)])

Logs an error message.

Source

pub fn fatal(&self, msg: &str, keyvals: &[(&str, &str)])

Logs a fatal message.

Source

pub fn logf(&self, level: Level, format: &str, args: &[&dyn Display])

Logs a message with formatting.

Source

pub fn debugf(&self, format: &str, args: &[&dyn Display])

Logs a debug message with formatting.

Source

pub fn infof(&self, format: &str, args: &[&dyn Display])

Logs an info message with formatting.

Source

pub fn warnf(&self, format: &str, args: &[&dyn Display])

Logs a warning message with formatting.

Source

pub fn errorf(&self, format: &str, args: &[&dyn Display])

Logs an error message with formatting.

Source

pub fn fatalf(&self, format: &str, args: &[&dyn Display])

Logs a fatal message with formatting.

Trait Implementations§

Source§

impl Clone for Logger

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Logger

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Logger

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl Freeze for Logger

§

impl RefUnwindSafe for Logger

§

impl Send for Logger

§

impl Sync for Logger

§

impl Unpin for Logger

§

impl UnwindSafe for Logger

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

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

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more