Search code examples
c#nlog

What's the best way to add a tag to each log message using Nlog?


I want to add specific tag to each log message inside different classes. Something like this:

class A
{
    private string tag = "Tag A";
    public DoSomething()
    {
        Logger.Debug("Some message",tag: tag);
    }
}

I found one solution:

Logger logger = LogManager.GetCurrentClassLogger();
LogEventInfo eventInfo = new LogEventInfo(LogLevel.Trace,  
    "Hello from RunJob", logger.Name);
eventInfo.Properties["CustomerID"] = "someCustID";
eventInfo.Properties["TargetSite"] "someTargetSite";

logger.Log(eventInfo);

But perhaps there is some simpler way? At the moment I'm thinking of creating a wrapper.


Solution

  • It was pretty easy

    logger.WithProperty("myProperty", "myValue").Info("Hello");
    

    https://github.com/NLog/NLog/wiki/Context