如何使用 NLog 记录调用方法及其传入参数?如果不可能:我可以将一些参数传递给记录器,以便它们出现在最终的日志消息中吗?
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);
Run Code Online (Sandbox Code Playgroud)
然后可以使用提取${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 引入了一个新的Fluent-Logger-API,它以最小的开销捕获源文件 + 行号 + 类名,以便与${callsite:captureStackTrace=false}一起使用:
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);
Run Code Online (Sandbox Code Playgroud)