使用Nlog messageGeneratorFunc和结构化日志

时间:2019-01-08 20:34:58

标签: c# nlog

使用Log.Info编写结构化日志很酷:

Log.Info("The record {id} has firstname {firstname} and lastname {lastname}",
    record.Id, record.FirstName, record.LastName)

我经常使用Debug方法。在我将它们包装在Log.IsDebugEnabled中但开始使用messageGeneratorFunc变体之前,

Log.Debug(() => string.Format("The record {0} has firstname {1} and lastname {2}",
    record.Id, record.FirstName, record.LastName);

我想知道如何将结构化日志记录与messageGeneratorFunc一起使用?

Log.Debug(() => Log.Debug("The record {id} has firstname {firstname} and lastname {lastname}",
    record.Id, record.FirstName, record.LastName

看起来很奇怪... Log.Debug Log.Debug,但是可以正常工作... IsDebugEnabled的内部检查发生了两次...是否有适当的选择?或者应该是什么样子?

1 个答案:

答案 0 :(得分:1)

messageGeneratorFunc-delegate用于重型/大型对象的专门序列化。未启用LogLevel时,NLog不会调用委托。

使用messageGeneratorFunc-delegate处理简单的消息模板没有任何意义。实际上,这只会损害性能,因为即使未启用LogLevel,也总是需要进行委托捕获。

这便宜又快捷:

Log.Debug("The record {0} has firstname {1} and lastname {2}",
    record.Id, record.FirstName, record.LastName);

Log.Debug("The record {id} has firstname {firstname} and lastname {lastname}",
    record.Id, record.FirstName, record.LastName);

比这样做(取消优化):

Log.Debug(() => string.Format("The record {0} has firstname {1} and lastname {2}",
    record.Id, record.FirstName, record.LastName);

另请参见NLog教程:Logger should handle string formatting