Serialize+log all function parameters in case of error

Hi,

I have a function that processes lots of live data. Sometimes it gives an error I don't yet understand. Due to the volume of data, it would be impractical to just log all the inputs and search for the problem later. The function returns a Result and all parameters implement Serialize. Is there some crate that provides a proc_macro like this:

#![log_in_case_of_err("/var/log/interesting-input-%d.json")]
fn my_function(a : f32, b : Vec<u8>) {
  // mysterious behavior going on in here
}

which would serialize all inputs that produce an Err to some file that could look like this:

{
  "a": NaN,
  "b": [2, 4, 6, 8]
}

I don't really have a good idea what to google for; does something like this already exist or will this be my project to finally learn macros?

tracing/tracing at master · tokio-rs/tracing · GitHub, which is also used in rustc Using the tracing/logging instrumentation - Guide to Rustc Development

1 Like

I guess the #[instrument] attribute macro from tracing qualifies as somewhat equivalent to the OPs description. But the resulting log message is probably too verbose? Maybe I just don't know how to properly configure tracing. Here is how I'd use tracing for this:

/*
[dependencies]
tracing = "*"
tracing-subscriber = { version = "*", features = ["json"] }
*/
use tracing::instrument;

use tracing_subscriber;

#[instrument(err)]
fn my_function(a : f32) -> Result<f32, &'static str> {
  (a > 0.).then_some(a).ok_or("error") 
}


fn main() {
    tracing_subscriber::fmt().json().init();
    
    assert!(my_function(1.).is_ok());
    
    assert!(my_function(-1.).is_err());
}

Log output:

{"timestamp":"2023-02-07T16:16:50.974955Z","level":"ERROR","fields":{"error":"error"},"target":"playground","span":{"a":-1.0,"name":"my_function"},"spans":[{"a":-1.0,"name":"my_function"}]}

Rustexplorer.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.