How to log calling method with its incoming parameters using NLog? If it's not possible: can I pass some parameters to logger, so that they will appear in the final log message?
2 Answers
NLog allows you to capture additional context with the 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);
Can then be extracted using ${all-event-properties}
See also: https://github.com/NLog/NLog/wiki/EventProperties-Layout-Renderer
See also: https://github.com/NLog/NLog/wiki/All-Event-Properties-Layout-Renderer
You can automatically capture method-name by creating your own log-method with [System.Runtime.CompilerServices.CallerMemberName] methodName
as parameter. See also: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute
And if using LogManager.GetCurrentClassLogger()
to acquire the logger for the class, then you can use ${logger}
to render the class-name.
NLog v5 introduces a new fluent-Logger-API, that captures source-file + line-number + class-name with minimal overhead for use with ${callsite:captureStackTrace=false}:
_logger.ForInfoEvent()
.Message("This is a fluent message {0}", "test")
.Property("PropertyName", "PropertyValue")
.Log();

- 17,785
- 1
- 51
- 70
-
1nlog have a build-in renderer ${callsite} for namespace + classname + method name. https://github.com/NLog/NLog/wiki/Callsite-layout-renderer – Vladislav Apr 29 '20 at 11:48
-
@Vladislav Yes but it has a performance penalty. Unless calling LogEventInfo.SetCallerInfo https://nlog-project.org/documentation/v4.7.0/html/M_NLog_LogEventInfo_SetCallerInfo.htm (And using NLog 5.0) – Rolf Kristensen Apr 29 '20 at 16:24
One of ways to solve this - create custom wrapper under NLog logger class, that will take extra params like className and methodName. After that construct message yourself. You can use this also: