如何替换此代码:
string name = "John";
logger.Information("length of name '{name}' is {nameLength}", name, name.Length);
像这样或类似的C#字符串插值
string name = "John";
// :-( lost benefit of structured logging: property names not passed to logger
logger.Information($"length of name '{name}' is {name.Length}");
但是保留用于结构化日志记录的属性名称吗?
将此文件添加到您的项目。它具有ILogger
扩展方法VerboseInterpolated()
,DebugInterpolated()
等等。这里也有单元测试。
string name = "John";
// add 'Interpolated' to method name: InformationInterpolated() instead of Information()
// add name of the property after the expression. Name is passed to the logger
logger.InformationInterpolated($"length of name '{name:name}' is {name.Length:Length}");
但是要小心:使用错误的方法太容易了。例如logger.Debug($"length = {length:propertyNameForLogger}")
,如果您不小心使用了Serilog的方法,它将记录log length = propertyNameForLogger
,因此不会记录任何参数值。这是由于propertyNameForLogger
是格式为你的价值。
string name = "John";
// add 'Interpolated' to method name: InformationInterpolated() instead of Information()
// create an anonymous object with 'new { propertyName }'.
// It's much slower because of using Reflection, but allows to write the variable name only once.
logger.InformationInterpolated($"length of name '{new { name }}' is {new { name.Length }}");
// you can also specify other property names
logger.InformationInterpolated($"length of name '{new { userName = name }}' is {new { lengthOfName = name.Length }}");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句