Crate structured_logger
source ·Expand description
Structured Logger
A logging implementation for the log
crate that logs structured values
as JSON (CBOR, or any other) into a file, stderr, stdout, or any other.
To initialize the logger use Builder
.
Inspired by std-logger.
This crate provides only a logging implementation. To do actual logging use
the log
crate and it’s various macros.
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
use serde::Serialize;
use std::{fs::File, io::stdout};
use structured_logger::{json::new_writer, unix_ms, Builder};
fn main() {
// Initialize the logger.
// Optional: create a file to write logs to.
let log_file = File::options()
.create(true)
.append(true)
.open("app.log")
.unwrap();
// Builder::with_level("debug")
Builder::new()
// Optional: set a specific writer (format to JSON, write to stdout) for target "api".
.with_target_writer("api", new_writer(stdout()))
// Optional: set a specific writer (format to JSON, write to app.log file) for target "file".
.with_target_writer("file", new_writer(log_file))
.init();
let kv = ContextLog {
uid: "user123".to_string(),
action: "upate_book".to_string(),
};
log::info!("hello world");
// This log will be written to stderr (default writer):
// {"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 = log::as_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}
log::info!(target: "file",
method = "GET",
path = "/hello",
status = 200_u16,
start = unix_ms(),
elapsed = 10_u64,
kv = log::as_serde!(kv);
"",
);
// This log will be written to file "app.log":
// {"elapsed":10,"kv":{"uid":"user123","action":"upate_book"},"level":"INFO","message":"","method":"GET","path":"/hello","start":1679745592127,"status":200,"target":"file","timestamp":1679745592127}
}
#[derive(Serialize)]
struct ContextLog {
uid: String,
action: String,
}
Modules
- Async JSON Writer Implementation
- Sync JSON Writer Implementation
Structs
- A struct to initialize the logger.
Traits
- A trait that defines how to write a log.
Functions
- Returns the log level from the environment variables.
- Returns the current unix timestamp in milliseconds.