home ~ projects ~ socials

Customized Log Format Output In Rust With tracing

Introduction

I'm working on the interface for Neopoligen. The end goal is to get really good error messages. At the start, I'm just trying to make them readable. This is the code I'm using to do that.

```cargo
[dependencies]
tracing = "0.1"
tracing-subscriber = "0.3"
```
use tracing::{Level, event, instrument};
use tracing_subscriber::fmt;

#[instrument]
fn main() {
    let format = fmt::format()
      .without_time()
      .with_target(false)
      .with_ansi(false);
    tracing_subscriber::fmt()
      .event_format(format)
      .with_max_level(Level::DEBUG)
      .init();
  event!(Level::INFO, "This is an info message");
  event!(Level::DEBUG, "This is a debug message");
}
Output:
INFO This is an info message
DEBUG This is a debug message

Details

  • The code creates a custom tracing_subscriber formatter via tracing_subscriber::fmt::format() with calls to customize the output
  • Without applying the formatter, the output text would be:

    2024-04-23T14:14:56.835109Z INFO _active_nvim_run: This is the log message

  • .without_time() turns off the time stamp
  • .with_target(false) turns off some diagnostic info about the function that's running the code
  • The .with_ansi(false) line turns off formatting that adds colors for the terminal. Without it, you'd see something like:

    ^[[32m INFO ^[[0m This is the log message

-- end of line --

References