3

How to print what source line! and file! a trace log originated from with tracing and tracing-subscriber?

The code I'm working with is well prepared and contains lots of log prints, which is good, but most of them are not very descriptive:

# Cargo.toml
[dependencies]
tracing = "0.1.35"
tracing-subscriber = "0.3.11"
tracing_subscriber::fmt::init();

// ...

if let Err(e) = important_work.await {
    tracing::info!(" {:?}", &e);
};

And the console prints only show module and error message, not where the code failed. When I replaced it with:

pub struct CustomLayer;

impl<S> Layer<S> for CustomLayer
where
    S: tracing::Subscriber,
{
    fn on_event(
        &self,
        event: &tracing::Event<'_>,
        _ctx: tracing_subscriber::layer::Context<'_, S>,
    ) {
         println!("{level}  name={:?}", event.metadata().name());
         for field in event.fields() {
            println!("  field={}", field);
         }
      }
}

   // Snip to main()

   tracing_subscriber::registry().with(CustomLayer).init();

I was able to get the file and line in event.metadata().name()) but then all error messages are turned into just the string "message". There is probably a simpler way of enabling printing of line numbers.

kmdreko
  • 42,554
  • 6
  • 57
  • 106
Simson
  • 3,373
  • 2
  • 24
  • 38

1 Answers1

7

You can customize the formatter as specified in the documentation. Some of the options are with_file() and with_line_number():

tracing_subscriber::fmt()
    .event_format(
        tracing_subscriber::fmt::format()
            .with_file(true)
            .with_line_number(true)
    )
    .init();

Example output (without colors ):

2022-07-12T06:05:35.654279Z  INFO playground: src/main.rs:16: abc

You can of course use additional options as you wish.

Jmb
  • 18,893
  • 2
  • 28
  • 55
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
  • These methods are available on `tracing_subscriber::fmt()` directly: `tracing_subscriber::fmt().with_file(true).with_line_number(true).init()` should be a bit more succinct. – kmdreko Sep 17 '22 at 02:25
  • If your Cargo project has dependency on another crate in the local file system (for example, `another-crate = {path="../another/crate"}` in the `Cargo.toml`) , Every call to the function `with_file(...)` in another crate exposes the full path of the crate file in a log event, you might need to avoid that for security concern. – Ham Jul 26 '23 at 08:57