Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log method name and parameters with NLog

Tags:

.net

nlog

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?

like image 699
0x49D1 Avatar asked Nov 12 '22 22:11

0x49D1


1 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();
like image 186
Rolf Kristensen Avatar answered Nov 15 '22 13:11

Rolf Kristensen