使用NLog记录方法名称和参数

6
如何使用NLog记录调用方法及其传入参数?如果不可能,我能否将一些参数传递给日志记录器,以便它们出现在最终的日志消息中?
2个回答

2
NLog允许您在LogEvent中捕获额外的上下文信息
Logger logger = LogManager.GetCurrentClassLogger();
LogEventInfo theEvent = new LogEventInfo(LogLevel.Debug, null, "Pass my custom value");
theEvent.Properties["MyValue"] = "My custom string";
theEvent.Properties["MyDateTimeValue"] = new DateTime(2015, 08, 30, 11, 26, 50);
theEvent.Properties["MyDateTimeValueWithCulture"] = new DateTime(2015, 08, 30, 11, 26, 50);
theEvent.Properties["MyDateTimeValueWithCultureAndFormat"] = new DateTime(2015, 08, 30, 11, 26, 50);
logger.Log(theEvent);

使用${all-event-properties}可以提取所有事件属性。

另见:https://github.com/NLog/NLog/wiki/EventProperties-Layout-Renderer

另见:https://github.com/NLog/NLog/wiki/All-Event-Properties-Layout-Renderer

通过创建自己的日志方法并将[System.Runtime.CompilerServices.CallerMemberName] methodName作为参数,可以自动捕获方法名称。另见:https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute

如果使用LogManager.GetCurrentClassLogger()获取类的记录器,则可以使用${logger}来呈现类名。

NLog v5引入了一个新的流畅的Logger API,它以最小的开销捕获源文件+行号+类名,可与${callsite:captureStackTrace=false}一起使用:

_logger.ForInfoEvent()
       .Message("This is a fluent message {0}", "test")
       .Property("PropertyName", "PropertyValue")
       .Log();

1
nlog内置了一个渲染器${callsite},用于命名空间+类名+方法名。https://github.com/NLog/NLog/wiki/Callsite-layout-renderer - Vladislav
@Vladislav 是的,但这会带来性能损失。除非调用LogEventInfo.SetCallerInfo https://nlog-project.org/documentation/v4.7.0/html/M_NLog_LogEventInfo_SetCallerInfo.htm(并使用NLog 5.0) - Rolf Kristensen

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接