英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论