Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

refactor(log): migrate from env_logger to tracing-subscriber

Maximilian Roos93812660c312
diff --git a/Cargo.lock b/Cargo.lock
index 907d69b07..d441d88fe 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1338,6 +1338,15 @@ version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
+[[package]]
+name = "matchers"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
+dependencies = [
+ "regex-automata",
+]
+
[[package]]
name = "memchr"
version = "2.7.6"
@@ -1453,6 +1462,15 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f5438dd2b2ff4c6df6e1ce22d825ed2fa93ee2922235cc45186991717f0a892d"
+[[package]]
+name = "nu-ansi-term"
+version = "0.50.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
+dependencies = [
+ "windows-sys 0.60.2",
+]
+
[[package]]
name = "num-conv"
version = "0.2.0"
@@ -2144,6 +2162,15 @@ dependencies = [
"digest 0.11.2",
]
+[[package]]
+name = "sharded-slab"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
+dependencies = [
+ "lazy_static",
+]
+
[[package]]
name = "shared_library"
version = "0.1.9"
@@ -2635,6 +2662,65 @@ version = "1.1.0+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d282ade6016312faf3e41e57ebbba0c073e4056dab1232ab1cb624199648f8ed"
+[[package]]
+name = "tracing"
+version = "0.1.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
+dependencies = [
+ "pin-project-lite",
+ "tracing-attributes",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-attributes"
+version = "0.1.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
+dependencies = [
+ "once_cell",
+ "valuable",
+]
+
+[[package]]
+name = "tracing-log"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
+dependencies = [
+ "log",
+ "once_cell",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-subscriber"
+version = "0.3.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
+dependencies = [
+ "matchers",
+ "nu-ansi-term",
+ "once_cell",
+ "regex-automata",
+ "sharded-slab",
+ "thread_local",
+ "tracing",
+ "tracing-core",
+]
+
[[package]]
name = "tree-sitter"
version = "0.26.8"
@@ -2731,6 +2817,12 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+[[package]]
+name = "valuable"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
+
[[package]]
name = "vergen"
version = "9.1.0"
@@ -3199,7 +3291,6 @@ dependencies = [
"dashmap",
"dirs",
"dunce",
- "env_logger",
"etcetera",
"fs2",
"home",
@@ -3242,6 +3333,9 @@ dependencies = [
"terminal_size",
"toml",
"toml_edit 0.25.5+spec-1.1.0",
+ "tracing",
+ "tracing-log",
+ "tracing-subscriber",
"tree-sitter",
"tree-sitter-bash",
"tree-sitter-highlight",
diff --git a/Cargo.toml b/Cargo.toml
index ab9f03fdb..e6f9ba641 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -38,10 +38,11 @@ cli = [
"dep:clap",
"dep:clap_complete",
"dep:crossterm",
- "dep:env_logger",
"dep:humantime",
"dep:skim",
"dep:termimad",
+ "dep:tracing-log",
+ "dep:tracing-subscriber",
]
syntax-highlighting = ["dep:tree-sitter", "dep:tree-sitter-bash", "dep:tree-sitter-highlight"]
# Enable shell/PTY integration tests (requires bash, zsh, fish installed on system)
@@ -83,10 +84,25 @@ clap = { version = "4.6", features = ["derive", "unstable-ext", "wrap_help"], op
clap_complete = { version = "4.6", features = ["unstable-dynamic"], optional = true }
crossbeam-channel = "0.5"
crossterm = { version = "0.29", optional = true }
-env_logger = { version = "0.11", optional = true }
indexmap = { version = "2.14", features = ["serde"] }
etcetera = "0.11"
+# `log` is still used pervasively for application logging; events flow into
+# `tracing` via `tracing-log::LogTracer` (CLI binary only).
log = "0.4"
+# 0.1.30 added the `enabled!` macro `src/trace/emit.rs::Span::drop` uses to
+# elide span emission when the subscriber doesn't care. Older versions only
+# expose the per-level macros and dispatcher checks.
+tracing = "0.1.30"
+# Compatibility shim: forward `log::*` macros into `tracing`. ~100 call sites
+# across the codebase keep using `log::debug!` etc.; only the routing layer
+# moved.
+tracing-log = { version = "0.2.0", optional = true }
+# Layered subscribers do the routing today's `Route` enum used to. `env-filter`
+# replaces env_logger's RUST_LOG parsing; `fmt` provides the writer + format
+# scaffolding; `registry` composes layers. Pinned to ≥ 0.3.17: that's when
+# `EnvFilter::builder().with_default_directive(...).from_env_lossy()` (used in
+# `src/logging.rs`) stabilized on top of the per-layer filtering rework.
+tracing-subscriber = { version = "0.3.17", default-features = false, features = ["ansi", "env-filter", "fmt", "registry"], optional = true }
# Only enable needed features - saves ~200KB by excluding debug, macros, multi_template
minijinja = { version = "2.19", default-features = false, features = ["builtins", "serde", "std_collections"] }
rayon = "1.12"
diff --git a/src/log_files.rs b/src/log_files.rs
index ca040d706..d7a433c5e 100644
--- a/src/log_files.rs
+++ b/src/log_files.rs
@@ -1,4 +1,4 @@
-//! On-disk log file sinks and routing for `-vv` debug output.
+//! On-disk log file sinks for `-vv` debug output.
//!
//! At `-vv`, two files are written in the repo's `.git/wt/logs/` directory:
//!
@@ -11,29 +11,25 @@
//!
//! Direct user-facing output (`info_message` / `eprintln!` from command
//! code) is unaffected — it goes to stderr at every verbosity level. This
-//! module governs only the `log::*` macro pipeline.
+//! module governs only the `log::*` / `tracing::*` macro pipeline.
//!
//! # Routing
//!
-//! [`route`] is the single source of truth for which sink a log record
-//! reaches. Invariants:
+//! Routing is performed structurally by the `tracing-subscriber` layers
+//! registered in `init_logging`:
//!
-//! - `SUBPROCESS_FULL_TARGET` records never reach stderr — raw bodies
-//! don't flood terminals. They go to `output.log` if active, else
-//! drop.
-//! - All other log records go to `trace.log` when it's active (`-vv`),
-//! and to stderr otherwise (e.g. `-v`, or `RUST_LOG=debug` without
-//! `-vv`). At `-vv` the `log::*` pipeline is silent on stderr — the
-//! user-facing `eprintln!` output stays, but the noisy `$ cmd`
-//! headers and subprocess previews land in the file.
+//! - The `output.log` layer filters to `SUBPROCESS_FULL_TARGET` only,
+//! so raw bodies never reach stderr or `trace.log`.
+//! - The `trace.log` layer accepts every record *except*
+//! `SUBPROCESS_FULL_TARGET` and writes to this file when `-vv` opened it.
+//! - The stderr layer is disabled at `-vv` (the file layers replace it)
+//! and otherwise honors `RUST_LOG` plus the `-v` baseline.
use std::fs::{File, OpenOptions};
-use std::io::Write;
+use std::io::{self, Write};
use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};
-use worktrunk::shell_exec::SUBPROCESS_FULL_TARGET;
-
pub(crate) struct LogSink {
file: OnceLock<Mutex<OpenFile>>,
filename: &'static str,
@@ -58,15 +54,19 @@ impl LogSink {
self.file.get().is_some()
}
- /// Append a line to the file (no-op if not initialized).
- ///
- /// The line should be plain text (no ANSI codes) for readability in bug
- /// reports. Write errors are swallowed — logging must not break commands.
- pub(crate) fn write_line(&self, line: &str) {
+ /// Append a whole formatted event (which may contain internal `\n`s) to
+ /// the file under a single lock acquisition. Trailing `\n` from the
+ /// fmt layer is stripped — `writeln!` adds its own — so multi-line
+ /// events stay grouped together rather than interleaving with another
+ /// thread's lines between intermediates. The line should be plain text
+ /// (no ANSI codes) for readability in bug reports. Write errors are
+ /// swallowed — logging must not break commands.
+ pub(crate) fn write_event(&self, text: &str) {
if let Some(mutex) = self.file.get()
&& let Ok(mut open) = mutex.lock()
{
- let _ = writeln!(open.file, "{}", line);
+ let body = text.trim_end_matches('\n');
+ let _ = writeln!(open.file, "{}", body);
let _ = open.file.flush();
}
}
@@ -77,6 +77,17 @@ impl LogSink {
.get()
.and_then(|mutex| mutex.lock().ok().map(|open| open.path.clone()))
}
+
+ /// Per-event `io::Write` adapter for use as a `tracing_subscriber`
+ /// `MakeWriter`. Buffers one event in memory, then forwards it as a
+ /// single locked append to the sink on drop — see [`Self::write_event`]
+ /// for why a multi-line event lands together.
+ fn writer(&'static self) -> SinkWriter {
+ SinkWriter {
+ sink: self,
+ buf: Vec::new(),
+ }
+ }
}
pub(crate) static TRACE: LogSink = LogSink {
@@ -91,48 +102,69 @@ pub(crate) static OUTPUT: LogSink = LogSink {
/// Initialize both log sinks.
///
/// Called once early in `main` when `-vv` or finer is active. Outside a git
-/// repo both sinks stay inactive and all writes become no-ops.
+/// repo both sinks stay inactive and all writes become no-ops. Run *before*
+/// the tracing subscriber is installed so the `Repository::current()` call
+/// here doesn't emit records to a half-built pipeline.
pub(crate) fn init() {
TRACE.init();
OUTPUT.init();
// Let shell_exec phrase the elision marker to match reality — points at
- // output.log when it exists, else suggests rerunning with -vv. The
- // false case at -vv (open failed asymmetrically) is benign here: the
- // user already got a "(output.log unavailable)" warning from the
- // startup pointer, so the marker's "rerun with -vv" text is just
- // redundant rather than misleading.
- worktrunk::shell_exec::set_output_log_available(OUTPUT.is_active());
+ // output.log when it exists, else suggests rerunning with -vv.
+ worktrunk::shell_exec::set_output_log_active(OUTPUT.is_active());
}
-/// Sink routing decision for one log record.
-pub(crate) enum Route {
- /// Append to this sink; skip stderr.
- File(&'static LogSink),
- /// Emit to stderr with normal formatting. Chosen when TRACE is
- /// inactive — the `-vv` path takes `File(&TRACE)` instead.
- Stderr,
- /// Drop the record entirely.
- Drop,
+/// Per-event writer: collects formatted bytes, then forwards them to the
+/// sink as one locked `write_event` call on drop.
+pub(crate) struct SinkWriter {
+ sink: &'static LogSink,
+ buf: Vec<u8>,
}
-/// Decide where a log record goes based on its target.
-///
-/// See module docs for the invariants each variant upholds.
-pub(crate) fn route(target: &str) -> Route {
- if target == SUBPROCESS_FULL_TARGET {
- if OUTPUT.is_active() {
- Route::File(&OUTPUT)
- } else {
- Route::Drop
- }
- } else if TRACE.is_active() {
- // -vv: send the noisy log pipeline to trace.log instead of stderr
- // so the user's terminal stays readable.
- Route::File(&TRACE)
- } else {
- // -v, or RUST_LOG=debug without -vv. `SUBPROCESS_BOUNDED_TARGET`
- // and all other targets share this path.
- Route::Stderr
+impl io::Write for SinkWriter {
+ fn write(&mut self, data: &[u8]) -> io::Result<usize> {
+ self.buf.extend_from_slice(data);
+ Ok(data.len())
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+}
+
+impl Drop for SinkWriter {
+ fn drop(&mut self) {
+ // `tracing_subscriber::fmt` always invokes the writer for an
+ // event (the formatter writes at least the trailing `\n`), so
+ // we don't need an empty-buffer guard here.
+ //
+ // Single-locked write: a multi-line event (the body has
+ // intermediate `\n`s) lands together in the file instead of
+ // interleaving with another thread's lines between
+ // intermediates. Nothing in this codebase emits multi-line
+ // tracing events today, but the contract holds if anything
+ // ever does.
+ let text = String::from_utf8_lossy(&self.buf);
+ self.sink.write_event(&text);
+ }
+}
+
+/// `MakeWriter` for the trace.log layer: always writes to `TRACE`.
+pub(crate) struct TraceMakeWriter;
+
+impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for TraceMakeWriter {
+ type Writer = SinkWriter;
+ fn make_writer(&'a self) -> SinkWriter {
+ TRACE.writer()
+ }
+}
+
+/// `MakeWriter` for the output.log layer: always writes to `OUTPUT`.
+pub(crate) struct OutputMakeWriter;
+
+impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for OutputMakeWriter {
+ type Writer = SinkWriter;
+ fn make_writer(&'a self) -> SinkWriter {
+ OUTPUT.writer()
}
}
@@ -149,3 +181,27 @@ fn try_create(filename: &str) -> Option<(PathBuf, File)> {
.ok()?;
Some((path, file))
}
+
+#[cfg(test)]
+mod tests {
+ use std::io::Write;
+
+ use super::{LogSink, SinkWriter};
+
+ /// `tracing_subscriber::fmt` only ever uses `write` + drop, but
+ /// `io::Write` requires us to implement `flush`. The body is a
+ /// no-op; this test exists so codecov sees the line covered without
+ /// us having to add a `#[cfg(not(coverage))]`-style allow.
+ #[test]
+ fn sink_writer_flush_is_a_no_op() {
+ static SINK: LogSink = LogSink {
+ file: std::sync::OnceLock::new(),
+ filename: "test-flush.log",
+ };
+ let mut w = SinkWriter {
+ sink: &SINK,
+ buf: Vec::new(),
+ };
+ assert!(w.flush().is_ok());
+ }
+}
diff --git a/src/logging.rs b/src/logging.rs
new file mode 100644
index 000000000..2bc0b8de1
--- /dev/null
+++ b/src/logging.rs
@@ -0,0 +1,429 @@
+//! Tracing-subscriber setup for the `wt` binary.
+//!
+//! Three layered subscribers cooperate to give each verbosity level the
+//! routing it needs. Filtering is structural (per-layer `Filter`), not done
+//! after-the-fact in a format closure:
+//!
+//! | layer | filter | format |
+//! | ----------- | ------------------------------------------------- | ----------------- |
+//! | stderr | off at `-vv`; else `$RUST_LOG` or `-v` baseline | styled with ANSI |
+//! | `trace.log` | `-vv` only, excludes `SUBPROCESS_FULL_TARGET` | plain text |
+//! | `output.log`| `-vv` only, includes only `SUBPROCESS_FULL_TARGET`| raw (no prefix) |
+//!
+//! The `log` crate calls (used throughout the codebase) are bridged into
+//! `tracing` by [`tracing_log::LogTracer::init`] — every layer above sees
+//! both native `tracing::*` events and forwarded `log::*` records.
+
+use std::fmt::{self, Write as _};
+
+use color_print::cformat;
+use tracing::{Event, Subscriber};
+use tracing_subscriber::Layer;
+use tracing_subscriber::filter::{EnvFilter, FilterExt, LevelFilter, filter_fn};
+use tracing_subscriber::fmt::{FmtContext, FormatEvent, FormatFields, format::Writer};
+use tracing_subscriber::layer::SubscriberExt;
+use tracing_subscriber::registry::LookupSpan;
+use tracing_subscriber::util::SubscriberInitExt;
+use worktrunk::shell_exec::SUBPROCESS_FULL_TARGET;
+use worktrunk::styling::{eprintln, info_message};
+
+use crate::log_files::{self, OutputMakeWriter, TraceMakeWriter};
+use crate::output;
+
+/// Single-character thread label (e.g. `a`, `b`, …, `A`, …) used to group
+/// concurrent records by thread in stderr / trace.log output.
+fn thread_label() -> char {
+ let thread_id = format!("{:?}", std::thread::current().id());
+ let parsed = thread_id
+ .strip_prefix("ThreadId(")
+ .and_then(|s| s.strip_suffix(")"))
+ .and_then(|s| s.parse::<usize>().ok());
+ label_for_thread_index(parsed)
+}
+
+/// Pure helper: map a parsed `ThreadId` number to a single-char label.
+///
+/// `n == 0` → `'0'`; `1..=26` → `'a'..='z'`; `27..=52` → `'A'..='Z'`;
+/// everything else (including a `None` from a `ThreadId` whose `Debug`
+/// shape we don't recognize) → `'?'`. Tested via the branch coverage
+/// below — `thread_label` itself never sees `n == 0` or `n > 52` in
+/// practice, so its `unwrap_or` chain stays exercised only through
+/// `label_for_thread_index`.
+fn label_for_thread_index(n: Option<usize>) -> char {
+ let Some(n) = n else { return '?' };
+ if n == 0 {
+ '0'
+ } else if n <= 26 {
+ char::from(b'a' + (n - 1) as u8)
+ } else if n <= 52 {
+ char::from(b'A' + (n - 27) as u8)
+ } else {
+ '?'
+ }
+}
+
+/// Pull the rendered message out of a `tracing` event.
+///
+/// Native `tracing::debug!("…")` and `log::*`-bridged calls both put their
+/// rendered text in the `message` field, recorded as `&dyn Debug` (an
+/// `Arguments` instance). Other fields are ignored — every caller in
+/// worktrunk emits the message inline.
+fn event_message(event: &Event<'_>) -> String {
+ struct V(String);
+ impl tracing::field::Visit for V {
+ fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn fmt::Debug) {
+ if field.name() == "message" {
+ let _ = write!(&mut self.0, "{value:?}");
+ }
+ }
+ }
+ let mut v = V(String::new());
+ event.record(&mut v);
+ v.0
+}
+
+/// Pure helper: render a single log message for stderr with the thread
+/// label and the styling rules `StderrFormat` applies. Factored out so the
+/// branches (`$ cmd [ctx]`, `$ cmd`, ` ! err`, plain) can be unit-tested
+/// without standing up a `tracing` subscriber.
+fn style_stderr_line(thread_num: char, msg: &str) -> String {
+ if let Some(rest) = msg.strip_prefix("$ ") {
+ // Standalone tools (gh, glab) emit no `[ctx]` suffix.
+ let (command, worktree) = match rest.find(" [") {
+ Some(pos) => (&rest[..pos], &rest[pos..]),
+ None => (rest, ""),
+ };
+ cformat!("<dim>[{thread_num}]</> $ <bold>{command}</>{worktree}")
+ } else if msg.starts_with(" ! ") {
+ cformat!("<dim>[{thread_num}]</> <red>{msg}</>")
+ } else {
+ cformat!("<dim>[{thread_num}]</> {msg}")
+ }
+}
+
+/// Stderr formatter: replicates the legacy env_logger styling pre-migration.
+///
+/// `$ cmd [worktree]` headers bold the command. ` ! …` continuation lines
+/// (subprocess stderr) are reddened. Everything else gets the thread-label
+/// prefix.
+struct StderrFormat;
+
+impl<S, N> FormatEvent<S, N> for StderrFormat
+where
+ S: Subscriber + for<'a> LookupSpan<'a>,
+ N: for<'a> FormatFields<'a> + 'static,
+{
+ fn format_event(
+ &self,
+ _ctx: &FmtContext<'_, S, N>,
+ mut writer: Writer<'_>,
+ event: &Event<'_>,
+ ) -> fmt::Result {
+ let line = style_stderr_line(thread_label(), &event_message(event));
+ writeln!(writer, "{line}")
+ }
+}
+
+/// `trace.log` formatter: plain `[<thread>] <message>`, no ANSI, one line
+/// per event. Matches the on-disk layout pre-migration.
+struct TraceFileFormat;
+
+impl<S, N> FormatEvent<S, N> for TraceFileFormat
+where
+ S: Subscriber + for<'a> LookupSpan<'a>,
+ N: for<'a> FormatFields<'a> + 'static,
+{
+ fn format_event(
+ &self,
+ _ctx: &FmtContext<'_, S, N>,
+ mut writer: Writer<'_>,
+ event: &Event<'_>,
+ ) -> fmt::Result {
+ let thread_num = thread_label();
+ let msg = event_message(event);
+ writeln!(writer, "[{thread_num}] {msg}")
+ }
+}
+
+/// `output.log` formatter: the message verbatim. Subprocess bodies are
+/// already prefixed (` …` / ` ! …`) by `shell_exec::format_stream_full`.
+struct OutputFileFormat;
+
+impl<S, N> FormatEvent<S, N> for OutputFileFormat
+where
+ S: Subscriber + for<'a> LookupSpan<'a>,
+ N: for<'a> FormatFields<'a> + 'static,
+{
+ fn format_event(
+ &self,
+ _ctx: &FmtContext<'_, S, N>,
+ mut writer: Writer<'_>,
+ event: &Event<'_>,
+ ) -> fmt::Result {
+ writeln!(writer, "{}", event_message(event))
+ }
+}
+
+/// Install the tracing subscriber and bridge `log::*` calls.
+///
+/// Stage-by-stage:
+///
+/// 1. Set verbosity for downstream styling code (unchanged).
+/// 2. Open the file sinks before the subscriber registers, so the
+/// `Repository::current()` rev-parse fired by `try_create` doesn't emit
+/// records into a half-built pipeline. Pre-tracing-init `log::*` calls
+/// are dropped by the default no-op `log` logger, which is the right
+/// behavior — there's nothing meaningful to attribute the call to before
+/// the subscriber exists.
+/// 3. Build three layered subscribers, each gated by both a verbosity check
+/// and the relevant `LogSink::is_active()` so a failed file open turns
+/// its layer into a no-op rather than silently dropping records.
+/// 4. Bridge `log::*` into tracing via `LogTracer`. Idempotent on
+/// re-invocation (init is `.ok()`-discarded).
+/// 5. Announce the file destinations on stderr at `-vv`.
+pub(crate) fn init(verbose_level: u8) {
+ output::set_verbosity(verbose_level);
+
+ if verbose_level >= 2 {
+ log_files::init();
+ }
+
+ // Layers wrap a base `fmt::Layer` with a `Filter`. `Option<Layer>`
+ // is itself a `Layer` (no-op when `None`), so verbosity gates compose
+ // naturally with subscriber `.with(...)` calls.
+ let stderr_layer = build_stderr_layer(verbose_level);
+ let trace_layer = build_trace_layer(verbose_level);
+ let output_layer = build_output_layer(verbose_level);
+
+ // `try_init` fails only if a subscriber is already installed (the
+ // single-call-per-process contract). `wt`'s `main` runs `logging::init`
+ // exactly once, so the error is just defensive — discard it. The
+ // `LogTracer::init` below has the same shape for the same reason.
+ let _ = tracing_subscriber::registry()
+ .with(stderr_layer)
+ .with(trace_layer)
+ .with(output_layer)
+ .try_init();
+
+ // Forward `log::*` macros into `tracing`. Must come after subscriber
+ // init: `LogTracer::enabled` consults the tracing dispatcher.
+ //
+ // The builder's `with_max_level` caps `log::max_level()` — the static
+ // gate `log_enabled!` checks before format args are evaluated. Mirror
+ // the env-wins-when-set semantics the layer filters use (PR #2901):
+ // if `RUST_LOG` is set, its level wins; otherwise the verbosity flag
+ // baseline applies. Without an explicit cap, the default
+ // `LevelFilter::max()` would always pass the static check, forcing
+ // every `log::debug!(…)` site to evaluate its format args — exposing
+ // arithmetic that's safe today only because the macro short-circuits
+ // (e.g. `now_secs - cached.checked_at` in `list/ci_status` is fine
+ // under monotonic-ish clocks but panics when args are evaluated
+ // against a clock-skewed fixture).
+ let _ = tracing_log::LogTracer::builder()
+ .with_max_level(effective_log_max_level(verbose_level, rust_log_level()))
+ .init();
+
+ if verbose_level >= 2 {
+ announce_trace_destination();
+ }
+}
+
+/// Effective ceiling for `log::max_level` given the verbosity flag and the
+/// parsed `RUST_LOG` value. Env wins when set; otherwise the verbosity
+/// baseline (`0` → Warn, `1` → Info, `2+` → Debug) applies. Factored out
+/// so the merge logic can be tested without driving the process env.
+fn effective_log_max_level(
+ verbose_level: u8,
+ from_env: Option<log::LevelFilter>,
+) -> log::LevelFilter {
+ let baseline = match verbose_level {
+ 0 => log::LevelFilter::Warn,
+ 1 => log::LevelFilter::Info,
+ _ => log::LevelFilter::Debug,
+ };
+ from_env.unwrap_or(baseline)
+}
+
+/// Highest level mentioned in `$RUST_LOG`, or `None` if unset / unparsable.
+///
+/// `RUST_LOG=info,worktrunk=debug` returns `Some(Debug)` (the most permissive
+/// directive wins). The `EnvFilter` on the stderr / trace layers still does
+/// the per-target matching; this helper just lifts `log::max_level` high
+/// enough that `log::*` macros don't short-circuit before reaching the
+/// dispatcher.
+fn rust_log_level() -> Option<log::LevelFilter> {
+ let raw = std::env::var("RUST_LOG").ok()?;
+ raw.split(',')
+ .filter_map(|directive| {
+ // Each directive is either `level` or `target=level` (the level
+ // is the rightmost `=`-separated token). Unknown tokens parse
+ // as `None` and don't contribute to the ceiling.
+ let level_token = directive.rsplit('=').next().unwrap_or(directive).trim();
+ level_token.parse::<log::LevelFilter>().ok()
+ })
+ .max()
+}
+
+/// Stderr layer: off at `-vv` (the file layers take over). For `-v 0` and
+/// `-v`, the flag sets a baseline (`Off` / `Info`) and `RUST_LOG`, when
+/// set, overrides via the standard directive grammar — matching the
+/// env-wins-when-set convention (see PR #2901). Excludes
+/// `SUBPROCESS_FULL_TARGET` at all levels — raw bodies must never reach
+/// the terminal.
+fn build_stderr_layer<S>(verbose_level: u8) -> Option<impl Layer<S>>
+where
+ S: Subscriber + for<'a> LookupSpan<'a>,
+{
+ if verbose_level >= 2 {
+ return None;
+ }
+ let baseline = match verbose_level {
+ 0 => LevelFilter::OFF,
+ _ => LevelFilter::INFO,
+ };
+ let env_filter = EnvFilter::builder()
+ .with_default_directive(baseline.into())
+ .from_env_lossy();
+ let exclude_full = filter_fn(|meta| meta.target() != SUBPROCESS_FULL_TARGET);
+ let layer = tracing_subscriber::fmt::layer()
+ .with_writer(std::io::stderr)
+ .with_ansi(true)
+ .event_format(StderrFormat)
+ .with_filter(env_filter.and(exclude_full));
+ Some(layer)
+}
+
+/// `trace.log` layer: only when `-vv` opened the file. Captures everything
+/// at the Debug baseline (`RUST_LOG`, when set, overrides — e.g.
+/// `RUST_LOG=trace wt -vv` lifts the file to Trace) except
+/// `SUBPROCESS_FULL_TARGET` (raw bodies go to `output.log`).
+fn build_trace_layer<S>(verbose_level: u8) -> Option<impl Layer<S>>
+where
+ S: Subscriber + for<'a> LookupSpan<'a>,
+{
+ if verbose_level < 2 || !log_files::TRACE.is_active() {
+ return None;
+ }
+ let env_filter = EnvFilter::builder()
+ .with_default_directive(LevelFilter::DEBUG.into())
+ .from_env_lossy();
+ let exclude_full = filter_fn(|meta| meta.target() != SUBPROCESS_FULL_TARGET);
+ let layer = tracing_subscriber::fmt::layer()
+ .with_writer(TraceMakeWriter)
+ .with_ansi(false)
+ .event_format(TraceFileFormat)
+ .with_filter(env_filter.and(exclude_full));
+ Some(layer)
+}
+
+/// `output.log` layer: only `SUBPROCESS_FULL_TARGET` records, raw passthrough.
+fn build_output_layer<S>(verbose_level: u8) -> Option<impl Layer<S>>
+where
+ S: Subscriber + for<'a> LookupSpan<'a>,
+{
+ if verbose_level < 2 || !log_files::OUTPUT.is_active() {
+ return None;
+ }
+ let only_full = filter_fn(|meta| meta.target() == SUBPROCESS_FULL_TARGET);
+ let layer = tracing_subscriber::fmt::layer()
+ .with_writer(OutputMakeWriter)
+ .with_ansi(false)
+ .event_format(OutputFileFormat)
+ .with_filter(only_full);
+ Some(layer)
+}
+
+/// Print a one-line stderr pointer at `-vv` so users know where the noisy
+/// log pipeline output went. Silent if `trace.log` couldn't be opened
+/// (outside a git repo, permission error) — there's nothing meaningful to
+/// point at.
+fn announce_trace_destination() {
+ // TRACE and OUTPUT open independently — `LogSink::init` succeeds per
+ // file. The (Some, None) case (trace.log open, output.log failed) is
+ // rare but real (path-type mismatch, fs quota); the reverse is
+ // possible too but `output.log` alone has no `$ cmd` context, so we
+ // stay silent there.
+ let Some(trace_path) = log_files::TRACE.path() else {
+ return;
+ };
+ let trace_display = worktrunk::path::format_path_for_display(&trace_path);
+ let msg = match log_files::OUTPUT.path() {
+ Some(output_path) => {
+ let output_display = worktrunk::path::format_path_for_display(&output_path);
+ cformat!(
+ "Tracing to <underline>{trace_display}</> (raw subprocess output @ <underline>{output_display}</>)"
+ )
+ }
+ None => cformat!("Tracing to <underline>{trace_display}</> (output.log unavailable)"),
+ };
+ eprintln!("{}", info_message(msg));
+}
+
+#[cfg(test)]
+mod tests {
+ use ansi_str::AnsiStr;
+
+ use super::{effective_log_max_level, label_for_thread_index, style_stderr_line};
+
+ /// Branch coverage for `label_for_thread_index` — `thread_label` never
+ /// hands it `n == 0` or `n > 52` in practice (Rust's `ThreadId`
+ /// numbering starts at 1 and the main process won't spawn 53+ threads
+ /// during the lifetime of the logger), but the branches are there for
+ /// the day either invariant changes.
+ #[test]
+ fn label_covers_each_branch() {
+ assert_eq!(label_for_thread_index(None), '?');
+ assert_eq!(label_for_thread_index(Some(0)), '0');
+ assert_eq!(label_for_thread_index(Some(1)), 'a');
+ assert_eq!(label_for_thread_index(Some(26)), 'z');
+ assert_eq!(label_for_thread_index(Some(27)), 'A');
+ assert_eq!(label_for_thread_index(Some(52)), 'Z');
+ assert_eq!(label_for_thread_index(Some(53)), '?');
+ assert_eq!(label_for_thread_index(Some(9999)), '?');
+ }
+
+ /// Each shape `StderrFormat` recognises — verified ANSI-stripped so
+ /// the assertions don't tangle with `cformat!`'s exact escape bytes.
+ #[test]
+ fn style_stderr_covers_each_shape() {
+ // `$ cmd [ctx]` — git path with worktree context.
+ let cmd_ctx = style_stderr_line('a', "$ git status [feature]")
+ .ansi_strip()
+ .into_owned();
+ assert_eq!(cmd_ctx, "[a] $ git status [feature]");
+
+ // `$ cmd` with no `[ctx]` — standalone tools (gh, glab) emit this
+ // shape; was line 109 in the codecov gap.
+ let cmd_no_ctx = style_stderr_line('b', "$ gh pr list")
+ .ansi_strip()
+ .into_owned();
+ assert_eq!(cmd_no_ctx, "[b] $ gh pr list");
+
+ // ` ! …` — subprocess stderr continuation, red-styled.
+ let err = style_stderr_line('c', " ! fatal: bad ref")
+ .ansi_strip()
+ .into_owned();
+ assert_eq!(err, "[c] ! fatal: bad ref");
+
+ // Plain — everything else falls through with just the thread prefix.
+ let plain = style_stderr_line('d', "hello").ansi_strip().into_owned();
+ assert_eq!(plain, "[d] hello");
+ }
+
+ /// `effective_log_max_level` mirrors the layer filters: env wins when
+ /// set, else the verbosity baseline. Driving it as a pure function
+ /// lets us cover the env-set branch without mutating the process env
+ /// (which races with parallel tests).
+ #[test]
+ fn effective_log_max_level_env_wins_when_set() {
+ use log::LevelFilter::*;
+ assert_eq!(effective_log_max_level(0, None), Warn);
+ assert_eq!(effective_log_max_level(1, None), Info);
+ assert_eq!(effective_log_max_level(2, None), Debug);
+ // Env raises:
+ assert_eq!(effective_log_max_level(0, Some(Debug)), Debug);
+ // Env lowers (the env-wins-when-set contract — env can also
+ // suppress, not just raise):
+ assert_eq!(effective_log_max_level(2, Some(Warn)), Warn);
+ }
+}
diff --git a/src/main.rs b/src/main.rs
index 658943b62..63c12aa7c 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,5 +1,4 @@
use std::collections::HashSet;
-use std::io::Write;
use std::path::Path;
use anyhow::Context;
@@ -31,6 +30,7 @@ pub(crate) mod help_pager;
mod invocation;
mod llm;
mod log_files;
+mod logging;
mod md_help;
mod output;
mod pager;
@@ -1225,151 +1225,6 @@ fn init_command_log(command_line: &str) {
}
}
-fn thread_label() -> char {
- let thread_id = format!("{:?}", std::thread::current().id());
- thread_id
- .strip_prefix("ThreadId(")
- .and_then(|s| s.strip_suffix(")"))
- .and_then(|s| s.parse::<usize>().ok())
- .map(|n| {
- if n == 0 {
- '0'
- } else if n <= 26 {
- char::from(b'a' + (n - 1) as u8)
- } else if n <= 52 {
- char::from(b'A' + (n - 27) as u8)
- } else {
- '?'
- }
- })
- .unwrap_or('?')
-}
-
-fn init_logging(verbose_level: u8) {
- // Configure logging based on --verbose flag, with `RUST_LOG` layered on
- // top. The flag sets the baseline filter level (`-v 0` → Off, `-v` →
- // Info, `-vv+` → Debug); `RUST_LOG`, when set, refines or overrides that
- // baseline via `env_logger`'s standard directive grammar. Examples:
- //
- // - bare `wt` → Off (silent)
- // - `RUST_LOG=debug wt` → Debug (env raises baseline)
- // - `wt -v` → Info
- // - `RUST_LOG=trace wt -vv` → Trace globally
- // - `RUST_LOG=worktrunk=trace wt -v` → Info + Trace for `worktrunk`
- //
- // All three flag levels go through the same builder shape — set the
- // baseline, then `parse_default_env()` — so `RUST_LOG` is honored
- // uniformly and never silently dropped. The flag still controls the
- // file-sink side effects: `-vv+` opens `.git/wt/logs/trace.log` and
- // `output.log`, and the `log::*` pipeline becomes silent on stderr
- // (the bounded preview lands in `trace.log` instead). User-facing
- // `eprintln!` output (template expansions, status, hints) is
- // unaffected at any level.
- output::set_verbosity(verbose_level);
-
- // Prime `GIT_COMMON_DIR_CACHE` BEFORE env_logger registers, so any
- // log records emitted while building the cache go nowhere (no logger
- // installed yet) and the later `Repository::current()` triggered by
- // `log_files::init` is a memory-cache hit with no fresh git call.
- // Without this, those records would fire while `TRACE.is_active()`
- // is still false (we're inside the call that sets the file) and
- // route to stderr — exactly the noise -vv is supposed to keep off
- // the terminal. Running before `.init()` also keeps the priming
- // robust if `Repository::current()` grows new log emissions later:
- // a not-yet-installed logger drops them harmlessly.
- //
- // Caveat: if priming itself fails (Ctrl-C during the ~5ms rev-parse
- // fork; transient fork error), the cache stays empty and the later
- // `log_files::init` re-runs the git call, which logs onto the
- // now-installed logger and leaks one `$ git rev-parse` line to
- // stderr. Rare and minor (one line, not 15K), so we don't engineer
- // around it; closing it cleanly requires resolving the log-dir path
- // without going through `shell_exec::Cmd`, which violates the
- // command-execution-through-Cmd invariant in CLAUDE.md.
- if verbose_level >= 2 {
- let _ = worktrunk::git::Repository::current();
- }
-
- let baseline = match verbose_level {
- 0 => log::LevelFilter::Off,
- 1 => log::LevelFilter::Info,
- _ => log::LevelFilter::Debug,
- };
- let mut builder = env_logger::Builder::new();
- builder.filter_level(baseline).parse_default_env();
-
- builder
- .format(|buf, record| {
- let route = log_files::route(record.target());
- let thread_num = thread_label();
- let msg = record.args().to_string();
-
- match route {
- log_files::Route::Drop => Ok(()),
- log_files::Route::File(sink) => {
- sink.write_line(&format!("[{thread_num}] {msg}"));
- Ok(())
- }
- log_files::Route::Stderr => {
- // Commands start with $, make only the command bold (not $ or [worktree])
- if let Some(rest) = msg.strip_prefix("$ ") {
- // Split: "git command [worktree]" -> ("git command", " [worktree]")
- // Standalone tools (gh, glab) emit no `[ctx]` suffix.
- let (command, worktree) = match rest.find(" [") {
- Some(pos) => (&rest[..pos], &rest[pos..]),
- None => (rest, ""),
- };
- writeln!(
- buf,
- "{}",
- cformat!("<dim>[{thread_num}]</> $ <bold>{command}</>{worktree}")
- )
- } else if msg.starts_with(" ! ") {
- // Error output - show in red
- writeln!(buf, "{}", cformat!("<dim>[{thread_num}]</> <red>{msg}</>"))
- } else {
- // Regular output with thread ID
- writeln!(buf, "{}", cformat!("<dim>[{thread_num}]</> {msg}"))
- }
- }
- }
- })
- .init();
-
- // Open per-file log sinks AFTER env_logger is registered so the
- // `Repository::current()` rev-parse fired by `try_create` is captured
- // in the trace. The startup pointer below uses the path resolved here.
- if verbose_level >= 2 {
- log_files::init();
- announce_trace_destination();
- }
-}
-
-/// Print a one-line stderr pointer at `-vv` so users know where the noisy
-/// `log::*` output went. Silent if `trace.log` couldn't be opened (outside
-/// a git repo, permission error) — there's nothing meaningful to point at.
-fn announce_trace_destination() {
- // TRACE and OUTPUT open independently — `LogSink::init` succeeds per
- // file. The (Some, None) case (trace.log open, output.log failed) is
- // rare but real (path-type mismatch, fs quota); the reverse is
- // possible too but `output.log` alone has no `$ cmd` context, so we
- // stay silent there.
- let Some(trace_path) = log_files::TRACE.path() else {
- return;
- };
- let trace_display = worktrunk::path::format_path_for_display(&trace_path);
- let msg = match log_files::OUTPUT.path() {
- Some(output_path) => {
- let output_display = worktrunk::path::format_path_for_display(&output_path);
- cformat!(
- "Tracing to <underline>{trace_display}</> (raw subprocess output @ <underline>{output_display}</>)"
- )
- }
- None => cformat!("Tracing to <underline>{trace_display}</> (output.log unavailable)"),
- };
- eprintln!("{}", info_message(msg));
-}
-
fn handle_merge_command(args: MergeArgs, yes: bool) -> anyhow::Result<()> {
if args.no_verify {
warn_no_verify_deprecated();
@@ -1630,16 +1485,18 @@ fn main() {
worktrunk::config::suppress_warnings();
}
- // `init_logging` registers the logger. Run it before `init_command_log`
- // so the latter's `Repository::current()` → `git rev-parse
- // --git-common-dir` subprocess is visible in `[wt-trace]` output. With
- // the previous order the rev-parse fired before any logger was
- // registered, leaving a 4ms hole in the trace where the subprocess
- // actually ran. Same reason `init_logging` itself reorders to
- // register env_logger before opening per-file log sinks.
+ // `logging::init` registers the tracing subscriber. Run it before
+ // `init_command_log` so the latter's `Repository::current()` →
+ // `git rev-parse --git-common-dir` subprocess is visible in
+ // `[wt-trace]` output. With the previous order the rev-parse fired
+ // before any subscriber was registered, leaving a 4ms hole in the
+ // trace where the subprocess actually ran. Same reason `logging::init`
+ // itself opens the per-file log sinks before installing the layers:
+ // the open's `Repository::current()` would otherwise emit into a
+ // half-built pipeline.
{
let _span = worktrunk::trace::Span::new("init_logging");
- init_logging(verbose);
+ logging::init(verbose);
}
// Fold the two cold-path rev-parses (`--git-common-dir` from
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index d84ad11ed..523e3b0ef 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -462,10 +462,9 @@ const LOG_OUTPUT_MAX_LINES: usize = 200;
/// addition to [`LOG_OUTPUT_MAX_LINES`].
const LOG_OUTPUT_MAX_BYTES: usize = 64 * 1024;
-/// Log target used for *full* subprocess stdout/stderr. The router in
-/// `log_files::route` sends records on this target to `output.log` only,
-/// so raw subprocess bodies (diffs, `git log -p`, patch-id pipelines)
-/// never reach stderr.
+/// Log target used for *full* subprocess stdout/stderr. The tracing-subscriber
+/// `output.log` layer filters on this target, so raw subprocess bodies (diffs,
+/// `git log -p`, patch-id pipelines) never reach stderr or `trace.log`.
pub const SUBPROCESS_FULL_TARGET: &str = "worktrunk::subprocess_full";
/// Log target used for the *bounded* preview of subprocess output (capped
@@ -479,7 +478,7 @@ pub const SUBPROCESS_BOUNDED_TARGET: &str = "worktrunk::subprocess_bounded";
/// `-vv`. Gates the phrasing of the elision marker so it doesn't promise a
/// file that wasn't created.
///
-/// The two-state split (available / not) intentionally collapses two
+/// The two-state split (active / not) intentionally collapses two
/// situations: (a) the user didn't run with `-vv` at all, and (b) the user
/// did but `output.log` failed to open (rare: path-type mismatch, FD
/// exhaustion). In (b), `announce_trace_destination` already warns at
@@ -489,25 +488,24 @@ pub const SUBPROCESS_BOUNDED_TARGET: &str = "worktrunk::subprocess_bounded";
///
/// Set by the binary's log-file init; stays `false` under `RUST_LOG=debug`
/// without `-vv`, where the full records are dropped by design.
-static OUTPUT_LOG_AVAILABLE: std::sync::atomic::AtomicBool =
- std::sync::atomic::AtomicBool::new(false);
+static OUTPUT_LOG_ACTIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Called from the binary once `log_files::init` has attempted to open
/// `output.log` — `yes` reflects whether that attempt succeeded.
-pub fn set_output_log_available(yes: bool) {
- OUTPUT_LOG_AVAILABLE.store(yes, std::sync::atomic::Ordering::Relaxed);
+pub fn set_output_log_active(yes: bool) {
+ OUTPUT_LOG_ACTIVE.store(yes, std::sync::atomic::Ordering::Relaxed);
}
/// Log captured stdout/stderr of a finished command.
///
-/// At `log::debug!` (`-vv`) each stream is emitted twice via separate log
-/// targets, and `log_files::route` directs them:
+/// At `tracing::DEBUG` (`-vv`) each stream is emitted twice via separate
+/// targets, and the tracing-subscriber layers route them:
/// - [`SUBPROCESS_FULL_TARGET`]: uncapped, line-per-record, `output.log` only.
/// - [`SUBPROCESS_BOUNDED_TARGET`]: capped at [`LOG_OUTPUT_MAX_LINES`] and
/// [`LOG_OUTPUT_MAX_BYTES`] per stream with an elision marker, then
/// routed to `trace.log` at `-vv` or stderr otherwise.
///
-/// Below `log::debug!` both targets are disabled and this is a no-op.
+/// Below Debug both targets are disabled and this is a no-op.
fn log_output(output: &std::process::Output) {
if !log::log_enabled!(log::Level::Debug) {
return;
@@ -540,7 +538,7 @@ fn format_stream_full(bytes: &[u8], prefix: &str) -> Vec<String> {
/// Split captured bytes into prefixed lines with at most [`LOG_OUTPUT_MAX_LINES`]
/// and [`LOG_OUTPUT_MAX_BYTES`] emitted; remainder replaced by a single
/// `… (N more lines, M bytes elided — <hint>)` marker. The hint text tracks
-/// whether `output.log` was opened (see [`set_output_log_available`]).
+/// whether `output.log` was opened (see [`set_output_log_active`]).
fn format_stream_bounded(bytes: &[u8], prefix: &str) -> Vec<String> {
if bytes.is_empty() {
return Vec::new();
@@ -555,7 +553,7 @@ fn format_stream_bounded(bytes: &[u8], prefix: &str) -> Vec<String> {
if lines_emitted >= LOG_OUTPUT_MAX_LINES || bytes_emitted >= LOG_OUTPUT_MAX_BYTES {
let remaining_lines = 1 + lines.count();
let remaining_bytes = total_bytes.saturating_sub(bytes_emitted);
- let hint = if OUTPUT_LOG_AVAILABLE.load(std::sync::atomic::Ordering::Relaxed) {
+ let hint = if OUTPUT_LOG_ACTIVE.load(std::sync::atomic::Ordering::Relaxed) {
"full output in output.log"
} else {
"rerun with -vv for full output"
@@ -2126,7 +2124,7 @@ mod tests {
marker.starts_with(" … (5 more lines, "),
"marker should count the 5 lines past the cap: {marker}"
);
- // OUTPUT_LOG_AVAILABLE defaults to false (only the binary's
+ // OUTPUT_LOG_ACTIVE defaults to false (only the binary's
// log_files::init sets it true), so the marker here suggests `-vv`.
assert!(marker.contains("rerun with -vv"));
}
diff --git a/src/testing/mod.rs b/src/testing/mod.rs
index c5ab41c7f..c9dc695a9 100644
--- a/src/testing/mod.rs
+++ b/src/testing/mod.rs
@@ -530,12 +530,12 @@ pub fn configure_cli_command(cmd: &mut Command) {
// by the env-strip above.
isolate_subprocess_env(cmd, None);
cmd.env("WORKTRUNK_TEST_EPOCH", TEST_EPOCH.to_string());
- // RUST_LOG intentionally NOT set: now that the flag baseline and
- // `RUST_LOG` merge via `env_logger::Builder::parse_default_env`
- // (env wins when set), a blanket `RUST_LOG=warn` default would cap
- // `-vv` tests at Warn and starve `trace.log` of debug-level
- // `[wt-trace]` records. Tests that need warn-level output should
- // opt in per-invocation.
+ // RUST_LOG intentionally NOT set: the flag baseline and `RUST_LOG`
+ // merge via the env-wins-when-set contract enforced by
+ // `tracing_subscriber::EnvFilter` (see `logging::init`), so a blanket
+ // `RUST_LOG=warn` default would cap `-vv` tests at Warn and starve
+ // `trace.log` of debug-level `[wt-trace]` records. Tests that need
+ // warn-level output should opt in per-invocation.
// Treat Claude as not installed by default (tests can override with "1")
cmd.env("WORKTRUNK_TEST_CLAUDE_INSTALLED", "0");
// Treat Codex as not installed by default (tests can override with "1")
diff --git a/src/trace/emit.rs b/src/trace/emit.rs
index 6f2f9008d..2e5100bc3 100644
--- a/src/trace/emit.rs
+++ b/src/trace/emit.rs
@@ -1,7 +1,7 @@
//! Authoritative emitter for the `[wt-trace]` log grammar.
//!
//! `[wt-trace]` records are structured single-line `key=value` text emitted on
-//! top of the `log` crate and parsed downstream by [`super::parse`] and the
+//! top of `tracing` and parsed downstream by [`super::parse`] and the
//! `wt-perf` binary. This module is the single source of truth for the
//! grammar — any field or formatting change happens here and in `parse.rs`
//! together.
@@ -22,10 +22,10 @@
//! in code paths subprocess records can't see (config load, repo open,
//! template render).
//!
-//! Records are emitted at `log::debug!`, so `-vv` or `RUST_LOG=debug` makes
+//! Records are emitted at `tracing::DEBUG`, so `-vv` or `RUST_LOG=debug` makes
//! them visible. Subprocess stdout/stderr continuations are emitted via
-//! separate log targets: the full output goes to `output.log`, and a bounded
-//! preview shares the routing of all other log records — `trace.log` at `-vv`,
+//! separate targets: the full output goes to `output.log`, and a bounded
+//! preview shares the routing of all other records — `trace.log` at `-vv`,
//! stderr otherwise — so raw bodies don't spam `-vv`.
use std::borrow::Cow;
@@ -69,7 +69,7 @@ pub fn command_completed(
ok: bool,
) {
match context {
- Some(ctx) => log::debug!(
+ Some(ctx) => tracing::debug!(
r#"[wt-trace] ts={} tid={} context={} cmd="{}" dur_us={} ok={}"#,
ts,
tid,
@@ -78,7 +78,7 @@ pub fn command_completed(
dur_us,
ok
),
- None => log::debug!(
+ None => tracing::debug!(
r#"[wt-trace] ts={} tid={} cmd="{}" dur_us={} ok={}"#,
ts,
tid,
@@ -99,7 +99,7 @@ pub fn command_errored(
err: impl Display,
) {
match context {
- Some(ctx) => log::debug!(
+ Some(ctx) => tracing::debug!(
r#"[wt-trace] ts={} tid={} context={} cmd="{}" dur_us={} err="{}""#,
ts,
tid,
@@ -108,7 +108,7 @@ pub fn command_errored(
dur_us,
err
),
- None => log::debug!(
+ None => tracing::debug!(
r#"[wt-trace] ts={} tid={} cmd="{}" dur_us={} err="{}""#,
ts,
tid,
@@ -125,7 +125,7 @@ pub fn command_errored(
/// Instant events appear as vertical lines in Chrome Trace Format tools
/// (chrome://tracing, Perfetto).
pub fn instant(event: &str) {
- log::debug!(
+ tracing::debug!(
r#"[wt-trace] ts={} tid={} event="{}""#,
now_us(),
thread_id(),
@@ -139,7 +139,7 @@ pub fn instant(event: &str) {
/// records cover work in child processes; spans cover everything between and
/// around them (config load, repo open, template render, etc.).
pub fn span_completed(name: &str, ts: u64, tid: u64, dur_us: u64) {
- log::debug!(
+ tracing::debug!(
r#"[wt-trace] ts={} tid={} span="{}" dur_us={}"#,
ts,
tid,
@@ -158,11 +158,11 @@ pub fn span_completed(name: &str, ts: u64, tid: u64, dur_us: u64) {
/// useful when the span name carries dynamic context, e.g.
/// `Span::new(format!("prepare_steps:{}", alias))`.
///
-/// The `log_enabled!` check happens on drop, not construction. A span
-/// constructed before `init_logging` (e.g. wrapping the logger init itself)
-/// still fires correctly as long as the logger is up by the time the span
-/// goes out of scope. Construction always pays two `Instant::now()` calls;
-/// they're vDSO-fast and the overhead is below noise.
+/// The `tracing::enabled!` check happens on drop, not construction. A span
+/// constructed before the subscriber is installed (e.g. wrapping the logger
+/// init itself) still fires correctly as long as the subscriber is up by the
+/// time the span goes out of scope. Construction always pays two
+/// `Instant::now()` calls; they're vDSO-fast and the overhead is below noise.
pub struct Span {
name: Cow<'static, str>,
start_ts_us: u64,
@@ -181,7 +181,7 @@ impl Span {
impl Drop for Span {
fn drop(&mut self) {
- if !log::log_enabled!(log::Level::Debug) {
+ if !tracing::enabled!(tracing::Level::DEBUG) {
return;
}
let dur_us = self.start.elapsed().as_micros() as u64;
diff --git a/tests/integration_tests/ci_status.rs b/tests/integration_tests/ci_status.rs
index dc17a427e..8e910a22a 100644
--- a/tests/integration_tests/ci_status.rs
+++ b/tests/integration_tests/ci_status.rs
@@ -482,8 +482,9 @@ platform = "invalid_platform"
// The snapshot asserts on the `log::warn!` diagnostic for the
// invalid platform value, which is suppressed at the default
// baseline filter (`-v 0` → Off). Opt this test into Warn-level
- // logging via `RUST_LOG`, which the verbose flag now merges with
- // through `env_logger::Builder::parse_default_env` (`init_logging`).
+ // logging via `RUST_LOG`, which `logging::init` merges with the
+ // verbose flag via `tracing_subscriber::EnvFilter` (env wins
+ // when set).
cmd.env("RUST_LOG", "warn");
// Invalid platform should fall back to URL detection (GitHub)
assert_cmd_snapshot!(cmd);
diff --git a/tests/integration_tests/diagnostic.rs b/tests/integration_tests/diagnostic.rs
index a040dad06..8455d641f 100644
--- a/tests/integration_tests/diagnostic.rs
+++ b/tests/integration_tests/diagnostic.rs
@@ -449,9 +449,9 @@ fn test_vv_log_pipeline_silent_on_stderr(repo: TestRepo) {
/// `RUST_LOG` is honored at every verbosity level — including `-v` — and
/// can raise the filter above the flag's baseline. A user who runs
/// `RUST_LOG=debug wt -v` gets Debug, not Info: the flag sets a baseline,
-/// and `RUST_LOG` refines it on top via `env_logger`'s standard directive
-/// grammar. Guards against the regression where `-v`/`-vv` hardcoded
-/// `filter_level(...)` without `parse_default_env()` and silently dropped
+/// and `RUST_LOG` refines it on top via `tracing_subscriber::EnvFilter`'s
+/// directive grammar (env wins when set). Guards against the regression
+/// where `-v`/`-vv` hardcoded `filter_level(...)` and silently dropped
/// `RUST_LOG`.
///
/// The probe is the `[wt-trace]` grammar — those records are emitted at