Search code examples
c#formattingserilog

Custom formatting of Timespans in Serilog


I'm trying to log some metrics with Serilog in order to monitor how a background process is going. A few of the metrics are TimeSpans that track the total time of the run, the time per iteration, etc. In my log message, they are currently formatted as {Elapsed:g} and {Total:g}. Their output is currently a little too verbose for my taste. For instance, I don't really need days, hours, or even minutes in the per-iteration log message because each iteration takes a second or so. Furthermore, I don't need days or hours in the cumulative message because the job cuts off after 30 minutes and lets the next run pick up where it left off.

I expected to be able to customize my formatting by saying something like {Elapsed:ss.fff}, but at runtime I will get an error, "System.FormatException: Input string was not in a correct format".

I could, of course, format the TimeSpan before passing it in to the logging call, but then I'd be working against the idea of structured logging. I want to log the pure data. I just want the human-readable message to be a bit more compact. Is that too much to ask?


Solution

  • For anyone also looking for this, I got it to work using double backslashes. For example:

    _logger.LogInformation("{Time:m\\:ss\\.fff}", timespan);