-
Notifications
You must be signed in to change notification settings - Fork 15
Description
KV support is already implemented and available in #77, so we can go further and add some very convenient features based on KV.
When using spdlog-rs for my personal projects, I find that sometimes I need to pass some contextual information repeatedly across multiple logging (or anyhow) macros, which is tedious and sometimes forgotten.
Basically, it's somewhat similar to tracing's span! (yes, inspired by it). The initial appearance design is (pseudo-code):
#[spdlog::contextual]
fn fetch_update(config) -> Result {
let username = get_username(config);
let receipt = get_receipt(config);
context!(username, chat = receipt.name); // Save the KVs with TID(?) as association, via a RAII guard
send_message(receipt.id, generate_message(username))
}
#[spdlog::contextual(arg)] // `arg` indicates saving the arguments automatically
fn send_message(chat_id, message) -> Result {
let url = format!(...);
context!(url); // Same as above
http_get(url).inspect(|err| {
error!("failed to send message", kv: { err }) // Write with the saved context KVs
})?;
}If sending fails, the log will be output:
[error] failed to send message { username=xxx chat=my group chat_id=12345 message=hello world url=https://example.com/sendMessage err=network unstable }
This may not work very well for patterns that handle errors at the top level, like I mentioned in #58. However, consider that there are indeed cases of on-the-spot log writes and tracing crate is widely used, maybe this feature should be implemented and #58 could also be re-opened and planned to be implemented as a harmless addition.