Expand description
§Structured Logger
A logging implementation for the log
crate that logs structured values either synchronous or asynchronous, in JSON, CBOR, or any other format, to a file, stderr, stdout, or any other destination. To initialize the logger use the Builder
struct. It is inspired by std-logger.
This crate provides only a logging implementation. To do actual logging use the log
crate and it’s various macros.
§Limiting logging targets
You can use Builder::with_target_writer
method to log messages related specific target to a specific writer.
§Crate features
This crate has three features:
log-panic
, enabled by default.
§Log-panic feature
The log-panic
feature will log all panics using the error
severity, rather then using the default panic handler. It will log the panic message as well as the location and a backtrace, see the log output for an panic_log
example.
§Examples
- Log panics example: https://github.com/iorust/structured-logger/blob/main/examples/panic_log.rs
- Async log example: https://github.com/iorust/structured-logger/blob/main/examples/async_log.rs
Simple example:
use serde::Serialize; use structured_logger::{async_json::new_writer, unix_ms, Builder}; #[tokio::main] async fn main() { // Initialize the logger. Builder::with_level("info") .with_target_writer("*", new_writer(tokio::io::stdout())) .init(); // Or use the default: // structured_logger::init(); let kv = ContextLog { uid: "user123".to_string(), action: "upate_book".to_string(), }; log::info!("hello world"); // This log will be written to stdout: // {"level":"INFO","message":"hello world","target":"simple","timestamp":1679745592127} log::info!(target: "api", method = "GET", path = "/hello", status = 200_u16, start = unix_ms(), elapsed = 10_u64, kv:serde = kv; "", ); // This log will be written to stdout: // {"elapsed":10,"kv":{"uid":"user123","action":"upate_book"},"level":"INFO","message":"","method":"GET","path":"/hello","start":1679745592127,"status":200,"target":"api","timestamp":1679745592127} } #[derive(Serialize)] struct ContextLog { uid: String, action: String, }
Modules§
- async_
json - Async JSON Writer Implementation
- json
- Sync JSON Writer Implementation
Structs§
Traits§
- Writer
- A trait that defines how to write a log. You can implement this trait for your custom formatting and writing destination.
Functions§
- get_
env_ level - Returns the log level from the environment variables:
LOG
,LOG_LEVEL
,RUST_LOG
,TRACE
orDEBUG
. Default isINFO
. - init
- Initializes the logger for
log
crate with default configuration. - log_
failure - A fallback logging function that is used in case of logging failure in
Writer
implementation. It will write failure information in JSON tostderr
. - unix_ms
- Returns the current unix timestamp in milliseconds.