James
James

Reputation: 1945

nlog to log to specific methods

I am using nlog to write logs to file. Currently when i log something then it logs everything from that class. I want to for example only log things which are failing in specific methods

public void myMethod(){
        try
        {
        }
        catch(Exception ex){
            Logger logger = NLog.LogManager.GetCurrentClassLogger();
            logger.Info("testing");
            logger.Log(LogLevel.Info, "Sample informational message");
        }
}

Upvotes: 0

Views: 1459

Answers (2)

Rolf Kristensen
Rolf Kristensen

Reputation: 19847

I'm guessing you want to capture the name of the class-method that is doing the logging (and not just the class-name).

This is called callsite in NLog (Can provide class-name, member-function-name , source-file and linenumber at callsite):

https://github.com/NLog/NLog/wiki/Callsite-layout-renderer

Activating the feature gives a huge overhead (Will capture full StackTrace for each log-event), so be careful when enabling it (But calling GetCurrentClassLogger() for every log-event is just as expensive).

Alternative you could capture the information yourself, by wrapping NLog-Logger and using the Caller Information Attributes (Much better performance):

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/caller-information

Upvotes: 1

Julian
Julian

Reputation: 36700

In this case you could use GetLogger instead of GetCurrentClassLogger

Logger logger = NLog.LogManager.GetLogger("myLogger");

In the config you could route/filter on the logger name:

<rule name="myLogger" minLevel="trace" writeTo="myFile"  />

Upvotes: 1

Related Questions