简体   繁体   中英

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?

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://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/caller-information

NLog is working on improving the performance of callsite, by making use of caller-information. See https://github.com/NLog/NLog/pull/2527

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM