自定义格式化 Serilog 中的时间跨度

huangapple go评论63阅读模式
英文:

Custom formatting of Timespans in Serilog

问题

我试图使用Serilog记录一些指标,以便监视后台进程的运行情况。其中一些指标是跟踪运行总时间、每次迭代的时间等的TimeSpans。在我的日志消息中,它们目前的格式为{Elapsed:g}{Total:g}。它们的输出目前对我来说有点太冗长了。例如,我在每次迭代的日志消息中实际上不需要天、小时,甚至不需要分钟,因为每次迭代只需要一秒左右。此外,在累积消息中,我不需要天或小时,因为作业在30分钟后截断,并允许下一次运行从上次中断的地方继续。

我期望能够通过类似{Elapsed:ss.fff}的方式自定义我的格式,但在运行时我会收到一个错误:“System.FormatException: 输入字符串的格式不正确”。

当然,我可以在传递给日志调用之前格式化TimeSpan,但那样我就违背了结构化日志的思想。我想记录纯数据。我只是希望人类可读的消息更紧凑一些。这是否太过分?

英文:

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?

答案1

得分: 0

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

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

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

huangapple
  • 本文由 发表于 2023年2月7日 05:18:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75366674.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定