macro_rules! init_context_logger {
($context_type:ty) => { ... };
($context_type:ty, $format:expr) => { ... };
}
Expand description
Macro to initialize the context logger
§Arguments
$context_type
- The type implementing the context$format
- Optional custom format string
§Examples
use with_async_context::{ContextLogger, init_context_logger, with_async_context, from_context_mut};
use log::{info, warn};
#[derive(Debug)]
struct MyContext {
function_name: String,
context_id: String,
}
impl ToString for MyContext {
fn to_string(&self) -> String {
format!("[{}:{}]", self.function_name, self.context_id)
}
}
// Initialize with default format
init_context_logger!(MyContext);
// Initialize with custom format
// init_context_logger!(MyContext, "{level} [{context}] {message}");
async fn example_function() {
from_context_mut(|ctx: Option<&mut MyContext>| {
if let Some(ctx) = ctx {
ctx.function_name = "example_function".to_string();
}
});
info!("Inside example function");
warn!("Something to warn about");
}
async fn another_function() {
from_context_mut(|ctx: Option<&mut MyContext>| {
if let Some(ctx) = ctx {
ctx.function_name = "another_function".to_string();
}
});
info!("Inside another function");
}
let ctx = MyContext {
function_name: String::new(),
context_id: "ctx1".to_string()
};
let (_, _) = with_async_context(ctx, example_function()).await;
let ctx2 = MyContext {
function_name: String::new(),
context_id: "ctx2".to_string()
};
let (_, _) = with_async_context(ctx2, another_function()).await;