How to show line number and file on tracing events?

Viewed 70

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.

1 Answers

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.

Related