diff --git a/AGENTS.md b/AGENTS.md index 5c759dc7..acd2eaf8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -57,8 +57,10 @@ and daemon detachment have explicit exceptions; do not reuse them for background work. Clippy and Oxlint enforce use of these helpers in CI. User-facing environment variables must use the `BRAINTRUST_` prefix (for -example `BRAINTRUST_DAEMON_SOCKET`), matching `bt` and the Braintrust SDKs. Do -not add new `BT_*` names. Read them through `bt-daemon/src/env.rs`; +example `BRAINTRUST_DAEMON_SOCKET`), matching `bt` and the Braintrust SDKs. +Variables that tune the trace daemon itself use the `BT_TRACE_` prefix (for +example `BT_TRACE_LOG_MAX_MB`) and are listed in `DAEMON_TUNING_ENV_VARS`. Do +not add other `BT_*` names. Read every variable through `bt-daemon/src/env.rs`; `DEPRECATED_BT_ENV_VARS` there only keeps old names working. `BT_TRACE_MANAGED_RUN_ID` and `BT_TRACE_INVOCATION_SETTINGS` remain the internal protocol between `bt trace run` and its child processes. diff --git a/bt-daemon/Cargo.lock b/bt-daemon/Cargo.lock index bafb41f1..3415aad3 100644 --- a/bt-daemon/Cargo.lock +++ b/bt-daemon/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "aho-corasick" version = "1.1.4" @@ -305,6 +311,7 @@ dependencies = [ "bytes", "chrono", "clap", + "file-rotate", "fs2", "libc", "muse-code-sdk", @@ -496,6 +503,15 @@ dependencies = [ "libc", ] +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + [[package]] name = "crossbeam" version = "0.8.4" @@ -675,12 +691,33 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "file-rotate" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e8e2fa049328a1f3295991407a88585805d126dfaadf74b9fe8c194c730aafc" +dependencies = [ + "chrono", + "flate2", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "fnv" version = "1.0.7" @@ -1347,6 +1384,16 @@ dependencies = [ "unicase", ] +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.2" @@ -2121,6 +2168,12 @@ dependencies = [ "libc", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "simd_cesu8" version = "1.2.0" @@ -2440,6 +2493,16 @@ dependencies = [ "tracing-core", ] +[[package]] +name = "tracing-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" +dependencies = [ + "serde", + "tracing-core", +] + [[package]] name = "tracing-subscriber" version = "0.3.23" @@ -2450,12 +2513,15 @@ dependencies = [ "nu-ansi-term", "once_cell", "regex-automata", + "serde", + "serde_json", "sharded-slab", "smallvec", "thread_local", "tracing", "tracing-core", "tracing-log", + "tracing-serde", ] [[package]] @@ -2982,6 +3048,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" diff --git a/bt-daemon/Cargo.toml b/bt-daemon/Cargo.toml index 87b69444..483d2fa4 100644 --- a/bt-daemon/Cargo.toml +++ b/bt-daemon/Cargo.toml @@ -45,9 +45,10 @@ thiserror = "2" tempfile = "3" tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "sync", "time", "process", "signal", "fs"] } tracing = "0.1" -tracing-subscriber = { version = "0.3", features = ["env-filter"] } +tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] } uuid = { version = "1", features = ["v4", "v5"] } rusqlite = { version = "0.37", features = ["bundled"] } +file-rotate = "0.8" [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_System_Threading"] } diff --git a/bt-daemon/README.md b/bt-daemon/README.md index f58e1eca..45352166 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -296,6 +296,14 @@ echo '{"session_id":"s1","hook_event_name":"Stop"}' | ./bt-daemon/target ``` The first `hook` spawns the daemon detached; it idles out after 5 minutes. +The daemon logs newline-delimited JSON to `daemon.log` in the data directory +at `debug`, and plain text to standard error at `warn` (`debug` with +`--verbose`). A spawned daemon's standard error is `serve.log`, so that file +holds only warnings and anything printed before logging starts. +`BT_TRACE_LOG_LEVEL` and `BT_TRACE_STDERR_LEVEL` override either filter in +`RUST_LOG` syntax. Each file is renamed to `.1`, replacing the previous +generation, once it would pass 10 MiB (`BT_TRACE_LOG_MAX_MB`), so the two +together hold the latest log in order. `import ` has a different purpose from restart recovery. It locates the native transcript in the selected agent's standard diff --git a/bt-daemon/src/client.rs b/bt-daemon/src/client.rs index 6d27740f..5386befe 100644 --- a/bt-daemon/src/client.rs +++ b/bt-daemon/src/client.rs @@ -191,11 +191,7 @@ fn spawn_daemon(host: &HostInfo, socket: &Path, data_dir_arg: Option<&Path>) -> .map(Path::to_path_buf) .unwrap_or_else(|| crate::paths::data_dir(None)); let _ = crate::paths::ensure_private_dir(&data_dir); - let log = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(data_dir.join("serve.log")) - .ok(); + let log = crate::daemon_log::open_serve_log(&data_dir).ok(); #[cfg(windows)] { diff --git a/bt-daemon/src/daemon_log.rs b/bt-daemon/src/daemon_log.rs new file mode 100644 index 00000000..2ce8fe82 --- /dev/null +++ b/bt-daemon/src/daemon_log.rs @@ -0,0 +1,252 @@ +//! The daemon's logging. Everything it logs goes through one `tracing` +//! subscriber with two outputs: +//! +//! - `daemon.log` in the data directory: newline-delimited JSON at `debug` +//! (`BT_TRACE_LOG_LEVEL`), for diagnosis after the fact. +//! - standard error: plain text at `warn`, or `debug` with `--verbose` +//! (`BT_TRACE_STDERR_LEVEL`). A spawned daemon's standard streams go to +//! `serve.log`, which therefore only holds warnings and anything printed +//! before logging starts. +//! +//! Both files are rotated by `file-rotate` once they pass +//! `BT_TRACE_LOG_MAX_MB` MiB (default [`DEFAULT_MAX_MB`]), keeping one earlier +//! generation as `.1`. `daemon.log` rotates as it is written; `serve.log` +//! rotates before a daemon is spawned, since the daemon writes it through an +//! inherited handle. +//! +//! The global subscriber can be set once per process, so a host that installs +//! its own must not do so before running the daemon command. + +use file_rotate::{compression::Compression, suffix::AppendCount, ContentLimit, FileRotate}; +use std::fs::{File, OpenOptions}; +use std::path::Path; +use std::sync::Mutex; +use tracing_subscriber::{fmt::MakeWriter, layer::SubscriberExt, EnvFilter, Layer}; + +/// Rotate once a log would grow past this many MiB. One earlier generation of +/// the same size is kept. +pub(crate) const DEFAULT_MAX_MB: u64 = 10; +pub(crate) const MAX_MB_ENV: &str = "BT_TRACE_LOG_MAX_MB"; +/// Filter for `daemon.log`, in `RUST_LOG` syntax. +pub(crate) const LEVEL_ENV: &str = "BT_TRACE_LOG_LEVEL"; +/// Filter for standard error, in `RUST_LOG` syntax. +pub(crate) const STDERR_LEVEL_ENV: &str = "BT_TRACE_STDERR_LEVEL"; + +/// The configured size limit in bytes. An unset, unparsable or zero value +/// uses the default, so logs stay bounded. +pub(crate) fn max_bytes() -> u64 { + limit(crate::env::var(MAX_MB_ENV).as_deref()) +} + +fn limit(mb: Option<&str>) -> u64 { + mb.and_then(|value| value.trim().parse::().ok()) + .filter(|mb| *mb > 0) + .unwrap_or(DEFAULT_MAX_MB) + .saturating_mul(1024 * 1024) +} + +/// Install the daemon's subscriber. Returns `false` if the process already +/// has one, which then keeps receiving the daemon's events. +pub(crate) fn init(data_dir: &Path, verbose: bool) -> bool { + let (subscriber, errors) = subscriber( + Mutex::new(rotating(&data_dir.join("daemon.log"))), + std::io::stderr, + // A spawned daemon's stderr is `serve.log`, which must stay plain. + std::io::IsTerminal::is_terminal(&std::io::stderr()), + verbose, + ); + if tracing::subscriber::set_global_default(subscriber).is_err() { + return false; + } + for error in errors { + tracing::warn!("{error}"); + } + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + tracing::error!(panic = %info, "daemon panicked"); + previous(info); + })); + true +} + +/// The daemon's subscriber, and any filter settings it had to reject. +fn subscriber( + file: F, + stderr: E, + ansi: bool, + verbose: bool, +) -> (impl tracing::Subscriber + Send + Sync, Vec) +where + F: for<'a> MakeWriter<'a> + Send + Sync + 'static, + E: for<'a> MakeWriter<'a> + Send + Sync + 'static, +{ + let (file_filter, file_error) = filter(LEVEL_ENV, "debug"); + let (stderr_filter, stderr_error) = + filter(STDERR_LEVEL_ENV, if verbose { "debug" } else { "warn" }); + let subscriber = tracing_subscriber::registry() + .with( + tracing_subscriber::fmt::layer() + .json() + .with_writer(file) + .with_filter(file_filter), + ) + .with( + tracing_subscriber::fmt::layer() + .with_ansi(ansi) + .with_writer(stderr) + .with_filter(stderr_filter), + ); + ( + subscriber, + [file_error, stderr_error].into_iter().flatten().collect(), + ) +} + +/// The filter named by `env`, or `default` with the reason it was rejected. +fn filter(env: &str, default: &str) -> (EnvFilter, Option) { + parse_filter(env, crate::env::var(env), default) +} + +fn parse_filter(env: &str, value: Option, default: &str) -> (EnvFilter, Option) { + match value { + Some(value) => match EnvFilter::try_new(&value) { + Ok(filter) => (filter, None), + Err(error) => ( + EnvFilter::new(default), + Some(format!("ignoring {env}={value:?}: {error}")), + ), + }, + None => (EnvFilter::new(default), None), + } +} + +/// A log at `path` that rotates once it passes the configured size, keeping +/// one earlier generation as `.1`. +fn rotating(path: &Path) -> FileRotate { + FileRotate::new( + path, + AppendCount::new(1), + ContentLimit::BytesSurpassed(usize::try_from(max_bytes()).unwrap_or(usize::MAX)), + Compression::None, + None, + ) +} + +/// Open `serve.log` for a new daemon's standard streams, rotating it first. +/// A daemon still exiting keeps writing into the rotated generation. +pub(crate) fn open_serve_log(data_dir: &Path) -> std::io::Result { + std::fs::create_dir_all(data_dir)?; + let path = data_dir.join("serve.log"); + let len = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0); + if len > max_bytes() { + if let Err(error) = rotating(&path).rotate() { + tracing::warn!(%error, "serve.log rotation failed"); + } + } + OpenOptions::new().create(true).append(true).open(path) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + + fn read(path: &Path) -> String { + std::fs::read_to_string(path).unwrap_or_default() + } + + #[test] + fn daemon_log_keeps_one_rotated_generation() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("daemon.log"); + let mut log = rotating(&path); + let line = vec![b'.'; 1024 * 1024]; + for _ in 0..(DEFAULT_MAX_MB * 3) { + log.write_all(&line).unwrap(); + } + log.flush().unwrap(); + let generations = std::fs::read_dir(dir.path()).unwrap().count(); + assert_eq!(generations, 2, "the current log and one rotated generation"); + assert!(dir.path().join("daemon.log.1").exists()); + assert!(std::fs::metadata(&path).unwrap().len() <= (DEFAULT_MAX_MB + 1) * 1024 * 1024); + } + + #[test] + fn serve_log_rotates_before_a_daemon_is_spawned() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("serve.log"); + std::fs::write( + &path, + vec![b'.'; (DEFAULT_MAX_MB * 1024 * 1024 + 1) as usize], + ) + .unwrap(); + let mut log = open_serve_log(dir.path()).unwrap(); + log.write_all(b"new daemon\n").unwrap(); + assert_eq!(read(&path), "new daemon\n"); + assert_eq!( + std::fs::metadata(dir.path().join("serve.log.1")) + .unwrap() + .len(), + DEFAULT_MAX_MB * 1024 * 1024 + 1 + ); + // Within the limit, the log is appended to as before. + drop(log); + open_serve_log(dir.path()) + .unwrap() + .write_all(b"again\n") + .unwrap(); + assert_eq!(read(&path), "new daemon\nagain\n"); + } + + #[test] + fn each_output_has_its_own_level_and_format() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("daemon.log"); + let stderr = Mutex::new(File::create(dir.path().join("stderr")).unwrap()); + let (subscriber, errors) = subscriber(Mutex::new(rotating(&path)), stderr, false, false); + assert!(errors.is_empty()); + tracing::subscriber::with_default(subscriber, || { + tracing::debug!(session_id = "s", "event received"); + tracing::warn!("delivery failed"); + }); + let lines: Vec = read(&path) + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + assert_eq!(lines.len(), 2, "the file records debug and above"); + assert_eq!(lines[0]["fields"]["message"], "event received"); + assert_eq!(lines[0]["fields"]["session_id"], "s"); + let stderr = read(&dir.path().join("stderr")); + assert!(stderr.contains("delivery failed"), "{stderr}"); + assert!( + !stderr.contains("event received"), + "stderr records warn and above" + ); + assert!(serde_json::from_str::(stderr.trim()).is_err()); + } + + #[test] + fn the_limit_is_a_positive_number_of_mib() { + assert_eq!(limit(Some(" 50 ")), 50 * 1024 * 1024); + for unusable in [None, Some(""), Some("0"), Some("-1"), Some("10MB")] { + assert_eq!( + limit(unusable), + DEFAULT_MAX_MB * 1024 * 1024, + "{unusable:?}" + ); + } + } + + #[test] + fn an_unusable_filter_falls_back_to_its_default() { + let (filter, error) = parse_filter(LEVEL_ENV, Some("bt_daemon=trace,warn".into()), "debug"); + assert_eq!(filter.to_string(), "bt_daemon=trace,warn"); + assert!(error.is_none()); + let (filter, error) = parse_filter(LEVEL_ENV, Some("bt_daemon=[".into()), "debug"); + assert_eq!(filter.to_string(), "debug"); + assert!(error.unwrap().starts_with("ignoring BT_TRACE_LOG_LEVEL")); + let (filter, error) = parse_filter(LEVEL_ENV, None, "debug"); + assert_eq!(filter.to_string(), "debug"); + assert!(error.is_none()); + } +} diff --git a/bt-daemon/src/env.rs b/bt-daemon/src/env.rs index 1ea1592e..763e21b1 100644 --- a/bt-daemon/src/env.rs +++ b/bt-daemon/src/env.rs @@ -1,13 +1,17 @@ //! User-facing environment variables use the `BRAINTRUST_` prefix, matching //! `bt` and the Braintrust SDKs. Read them through [`var_os`] so that the //! deprecated `BT_` names keep working until support is removed. +//! +//! Variables that tune the trace daemon itself use the `BT_TRACE_` prefix +//! instead and are listed in `DAEMON_TUNING_ENV_VARS`. They are read through +//! [`var_os`] like every other variable. use std::ffi::{OsStr, OsString}; /// Pre-`BRAINTRUST_` names of tracing env vars. Each `BT_` is still /// honored as an alias for `BRAINTRUST_` until support is removed in a /// major release. Do not add entries: new env vars must use the `BRAINTRUST_` -/// prefix. +/// prefix, or be daemon tuning listed in `DAEMON_TUNING_ENV_VARS`. /// /// `BT_TRACE_MANAGED_RUN_ID` and `BT_TRACE_INVOCATION_SETTINGS` are not listed: /// they are the internal protocol `bt trace run` uses to configure its child @@ -23,6 +27,15 @@ pub(crate) const DEPRECATED_BT_ENV_VARS: &[&str] = &[ "BT_TRACE_PI_PLUGIN_SPEC", ]; +/// Variables that tune the trace daemon itself rather than what it traces. +/// The prefix test below holds every `BT_*` name to this list. +#[cfg(test)] +pub(crate) const DAEMON_TUNING_ENV_VARS: &[&str] = &[ + crate::daemon_log::MAX_MB_ENV, + crate::daemon_log::LEVEL_ENV, + crate::daemon_log::STDERR_LEVEL_ENV, +]; + pub(crate) fn canonical_env_name(deprecated: &str) -> String { let name = deprecated.strip_prefix("BT_").unwrap_or(deprecated); format!("BRAINTRUST_{name}") @@ -91,8 +104,9 @@ mod tests { } /// New user-facing env vars must use the `BRAINTRUST_` prefix. Every - /// `BT_*` name in the crate must be a deprecated alias or internal protocol, - /// and every deprecated alias must map to a name the crate reads. + /// `BT_*` name in the crate must be a deprecated alias, internal protocol + /// or daemon tuning, and every deprecated alias must map to a name the + /// crate reads. #[test] fn env_vars_use_braintrust_prefix() { const INTERNAL: &[&str] = &[ @@ -117,7 +131,11 @@ mod tests { let unexpected: BTreeSet<_> = pattern .find_iter(&sources) .map(|m| m.as_str()) - .filter(|name| !DEPRECATED_BT_ENV_VARS.contains(name) && !INTERNAL.contains(name)) + .filter(|name| { + !DEPRECATED_BT_ENV_VARS.contains(name) + && !INTERNAL.contains(name) + && !DAEMON_TUNING_ENV_VARS.contains(name) + }) .collect(); assert!( unexpected.is_empty(), diff --git a/bt-daemon/src/lib.rs b/bt-daemon/src/lib.rs index 960229ba..cdcfa094 100644 --- a/bt-daemon/src/lib.rs +++ b/bt-daemon/src/lib.rs @@ -18,6 +18,7 @@ mod client; mod codex_hooks; mod command_output; mod correlation; +mod daemon_log; mod dispatch; mod env; mod hook; @@ -50,6 +51,12 @@ pub use args::{ HookArgs, ImportArgs, ImportSource, ParentObjectType, RunArgs, RunHookCommand, RunSource, ServeArgs, StatusArgs, }; +/// Install the daemon's logging: JSON to `daemon.log` in `data_dir` and plain +/// text to standard error, each with its own level and both rotated by size. +/// Returns `false` if the process already has a global subscriber. +pub fn init_daemon_logging(data_dir: &std::path::Path, verbose: bool) -> bool { + daemon_log::init(data_dir, verbose) +} pub use client::{ flush_managed_run, flush_session, forward_envelope, run_status, shutdown_daemon, HostInfo, }; diff --git a/bt-daemon/src/main.rs b/bt-daemon/src/main.rs index eb6118d5..37e76ba4 100644 --- a/bt-daemon/src/main.rs +++ b/bt-daemon/src/main.rs @@ -229,15 +229,18 @@ fn host_info() -> HostInfo { #[tokio::main] async fn main() { - tracing_subscriber::fmt() - .with_env_filter( - tracing_subscriber::EnvFilter::try_from_default_env() - .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), - ) - .with_writer(std::io::stderr) - .init(); - let cli = Cli::parse(); + // `serve` logs as the embedded daemon does; other development commands + // log to standard error. + if !matches!(cli.command, Command::Serve { .. }) { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), + ) + .with_writer(std::io::stderr) + .init(); + } match cli.command { Command::Serve { args, @@ -246,6 +249,7 @@ async fn main() { app_url, } => { let data_dir = paths::data_dir(args.data_dir.as_deref()); + bt_daemon::init_daemon_logging(&data_dir, false); let mut opts = if debug_sink { debug_serve_options(VERSION, &data_dir) } else { diff --git a/bt-daemon/src/server/ingress.rs b/bt-daemon/src/server/ingress.rs index c74c2eb9..e9a4be37 100644 --- a/bt-daemon/src/server/ingress.rs +++ b/bt-daemon/src/server/ingress.rs @@ -268,7 +268,7 @@ pub(super) async fn accept_resolved_event( let session_id = env.session_id.clone(); let managed_run_id = env.managed_run_id.clone(); let route = env.route.clone(); - tracing::info!(source, event, session_id, "event received"); + tracing::debug!(source, event, session_id, "event received"); let session_lock = daemon.dispatch_lock(&source, &session_id); let _session_guard = session_lock.lock().await; @@ -312,7 +312,7 @@ pub(super) async fn accept_resolved_event( .persist_managed_run_session(&managed_run_id, delivery_key, &route) .await; } - tracing::info!(source, event, session_id, "event accepted") + tracing::debug!(source, event, session_id, "event accepted") } Err(error) => tracing::warn!(source, event, session_id, %error, "event rejected"), } diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index d3269cca..45938ba5 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -211,15 +211,12 @@ fn host_info(host: &TraceHostContext) -> HostInfo { } } -fn init_daemon_logging(verbose: bool) { - let fallback = if verbose { "debug" } else { "info" }; - let filter = tracing_subscriber::EnvFilter::new(fallback); - if let Err(error) = tracing_subscriber::fmt() - .with_env_filter(filter) - .with_writer(std::io::stderr) - .try_init() - { - eprintln!("bt trace daemon logging unavailable: {error}"); +fn init_daemon_logging(data_dir: Option<&std::path::Path>, verbose: bool) { + let data_dir = paths::data_dir(data_dir); + if !crate::daemon_log::init(&data_dir, verbose) { + // A host installed a process-wide subscriber first; it can only be + // set once, so the daemon's events stay with the host's. + tracing::warn!("a logging subscriber is already installed; daemon logs go to it"); } } @@ -688,7 +685,7 @@ pub async fn run_trace(args: TraceArgs, host: TraceHostContext) -> anyhow::Resul print_output(output, host.output_format) } TraceCommand::Daemon(serve_args) => { - init_daemon_logging(host.verbose); + init_daemon_logging(serve_args.data_dir.as_deref(), host.verbose); run_serve(serve_args, serve_options(&host)).await } TraceCommand::Hook(hook_args) => {