use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogConfig {
#[serde(default = "default_level")]
pub level: String,
#[serde(default)]
pub components: HashMap<String, String>,
#[serde(default)]
pub json: bool,
}
fn default_level() -> String {
"info".to_string()
}
impl Default for LogConfig {
fn default() -> Self {
Self {
level: "info".into(),
components: HashMap::new(),
json: false,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TracingConfig {
#[serde(skip_serializing_if = "Option::is_none")]
pub otlp_endpoint: Option<String>,
#[serde(default = "default_service_name")]
pub service_name: String,
}
fn default_service_name() -> String {
"chaincodec".into()
}
pub fn init_tracing(config: &LogConfig) {
let mut directives = config.level.clone();
for (component, level) in &config.components {
directives.push_str(&format!(",{}={}", component.replace('-', "_"), level));
}
let filter = EnvFilter::try_new(&directives)
.unwrap_or_else(|_| EnvFilter::new("info"));
if config.json {
tracing_subscriber::registry()
.with(filter)
.with(fmt::layer().json())
.init();
} else {
tracing_subscriber::registry()
.with(filter)
.with(fmt::layer())
.init();
}
}