Howiecamp
Howiecamp

Reputation: 3111

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?

Upvotes: 3

Views: 5249

Answers (1)

Rolf Kristensen
Rolf Kristensen

Reputation: 19867

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();

Upvotes: 5

Related Questions