We have projects in VB and C# and they all have logging. Right now the implementation of a logger factory is causing memory leaks during load test. Looks like someone tried to hack the old code to support nlog and it creates counless instances of the log factory which is creating a lot of arrays and event handler leaks. I wanted to know what is the right approach to have a class that can be referenced in other projects to enable logging. Can we do something like
public interface ILogger{
void Error(string message);
void Debug(string message);
}
public NlogWrapper:ILogger{
private readonly NLog.Logger _logger;
public NLogLogger(string name)
{
_logger = NLog.LogManager.GetLogger(name);
}
Then in my other library projects I create logger insance such as
Private logger As ILogger = New NlogWrapper("Admin_" + DateTime.Now.ToString("yyyyMMdd"))
If you can the best method is probably to just use NLog directly wherever you can. The downside with this approach is that changing logging library will require changes to all projects, even if such changes might be fairly straightforward.
The recommended way to initialize a logger is
private static Logger logger = LogManager.GetCurrentClassLogger();
since this will limit the number of loggers to one per class. This would probably be my preferred alternative for new code.
WIth Microsoft extensions logging the initialization should look like
private readonly ILogger<MyClass> _logger;
public HomeController(ILogger<MyClass> logger)
{
_logger = logger;
}
As you can see this relies on dependency injection. More on nlog vs extension logging.
You could also create a single static logger for your entire application, but this would lose the possibility to filter logs on the typename, but that might be acceptable if the current code does not use that possibility.