1use serde::Serialize;
4use std::{fmt, io::Write};
5use tracing::{
6 field::{Field, Visit},
7 Event, Level, Subscriber,
8};
9use tracing_subscriber::{
10 filter::Targets,
11 layer::{Context, SubscriberExt},
12 util::SubscriberInitExt,
13 EnvFilter, Layer,
14};
15
16pub(crate) fn init(bal_report: bool) {
18 let client = std::env::var_os(EnvFilter::DEFAULT_ENV).filter(|v| !v.is_empty()).map(|value| {
19 tracing_subscriber::fmt::layer()
20 .with_writer(std::io::stderr)
21 .with_ansi(false)
22 .with_filter(EnvFilter::new(value.to_string_lossy()))
23 });
24 if client.is_none() && !bal_report {
25 return
26 }
27 let bal = bal_report.then(|| {
28 ExecutionPathLayer.with_filter(
29 Targets::new().with_target("engine::tree::bal_execution_path", Level::DEBUG),
30 )
31 });
32 tracing_subscriber::registry().with(client).with(bal).init();
33}
34
35struct ExecutionPathLayer;
37
38impl<S: Subscriber> Layer<S> for ExecutionPathLayer {
39 fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) {
40 let mut fields = ExecutionPathFields { event: "balExecution", ..Default::default() };
41 event.record(&mut fields);
42 let line = serde_json::to_string(&fields).expect("fields serialize");
43 let _ = writeln!(std::io::stderr().lock(), "{line}");
45 }
46}
47
48#[derive(Default, Serialize)]
50struct ExecutionPathFields {
51 event: &'static str,
52 block: u64,
53 hash: String,
54 path: String,
55 reason: String,
56}
57
58impl Visit for ExecutionPathFields {
59 fn record_u64(&mut self, field: &Field, value: u64) {
60 if field.name() == "block" {
61 self.block = value;
62 }
63 }
64
65 fn record_str(&mut self, field: &Field, value: &str) {
66 match field.name() {
67 "path" => self.path = value.to_string(),
68 "reason" => self.reason = value.to_string(),
69 _ => {}
70 }
71 }
72
73 fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
74 if field.name() == "hash" {
75 self.hash = format!("{value:?}");
76 }
77 }
78}