Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NLog - How do I get caller class name and method programmatically?

I'm using this https://github.com/NLog/NLog/tree/master/examples/ExtendingLoggers/LoggerWrapper method of extending NLog so that I can add custom properties to my events. So my code looks like this:

    public void WriteMessage(string eventID, string message)
    {
        LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, _logger.Name, message);

        logEvent.Properties["EventID"] = eventID;

        _logger.Log(typeof(MyLogger), logEvent);
    }

Within the WriteMessage method I tried to get the caller class and method names as follows:

logEvent.CallerClassName;
logEvent.CallerMemberName;

but both return null.

How can I get the values?

like image 947
Howiecamp Avatar asked Apr 19 '26 03:04

Howiecamp


1 Answers

Just like you can assign LogEventInfo.Exception then you can also assign LogEventInfo.CallerClassName (or LogEventInfo.CallerMemberName).

Calling the getter for LogEventInfo.Exception will only return an Exception-object if one assigned. The same goes for LogEventInfo.CallerClassName (or LogEventInfo.CallerMemberName)

The NLog Logger is responsible for doing capture of callsite. The Logger performs the capture when receiving the LogEventInfo. The capture is very expensive and only occurs if a target has been configured to use callsite.

Instead of trying to walk the StackTrace yourself. Then you might want to make use of caller-information: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/caller-information

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 103
Rolf Kristensen Avatar answered Apr 21 '26 15:04

Rolf Kristensen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!