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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With