Home > Blockchain >  nlog set global property by logger name
nlog set global property by logger name

Time:11-09

I want to instantiate a logger instance once and set some properties to it which can be used everywhere whenever I get the logger by that name, is this possible to do and how?

Example -

Logger logger = LogManager.GetLogger("MyLogger");

I want to set some properties on to this logger for my scheduled job with the job name -

logger.Property = job.Name;

Job.cs

public class Job{
Logger logger = LogManager.GetLogger("MyLogger");
logger.Property = job.Name;

//Call worker 
worker.Process();
}

Worker.cs

public class worker{
Logger logger = LogManager.GetLogger("MyLogger");
public static Process(){
 logger.Error("Test");
 }
}

Here in the worker I want to log the Job name, whats the best way to achieve this? I want to extend this to any further calls made from the job or the worker.

CodePudding user response:

You can consider to use the same Logger-instance everywhere, and use WithProperty:

public static class MyLogger {
     public static Logger Instance = NLog.LogManager.GetLogger("MyLogger").WithProperty("Hello", World");
}

public class Job{
   Logger logger = MyLogger.Instance;
   logger.Property = job.Name;

   //Call worker 
   worker.Process();
}

Alternative you can consider making use of MDLC (Task Scope Properties) or GDC (Global Scope Properties)

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

  • Related