See this answer here on SO for a brief example on the correct way to wrap the NLog Logger such that the call site information is preserved:
Problem matching specific NLog logger name
Here is another question that deals with wrapping the NLog Logger. Actually, the question is not about wrapping the NLog Logger, but my answer points out a problem in another answer's implementation of an NLog Logger wrapper.
What is the best way of using NLog with MEF?
The key is implementing your wrapper's logging methods in terms of NLog Logger.Log
method and passing the type
of your wrapper as the first parameter.
To save you some time, I've posted a slightly shortened version of the NLog Logger wrapper code here:
class NLogLogger : ILogger
{
private NLog.Logger logger;
public NLogLogger(Type t)
{
logger = NLog.LogManager.GetLogger(t.FullName);
}
//Trace, Warn, Error, Fatal eliminated for brevity
public bool IsInfoEnabled
{
get { return logger.IsInfoEnabled; }
}
public bool IsDebugEnabled
{
get { return logger.IsDebugEnabled; }
}
public void Info(string format, params object [] args)
{
if (logger.IsInfoEnabled)
{
Write(LogLevel.Info, format, args);
}
}
public void Debug(string format, params object [] args)
{
if (logger.IsDebugEnabled)
{
Write(LogLevel.Debug, format, args);
}
}
private void Write(LogLevel level, string format, params object [] args)
{
LogEventInfo le = new LogEventInfo(level, logger.Name, null, format, args);
logger.Log(typeof(NLogLogger), le);
}
}
You would use the wrapper like this:
class MyClass
{
private static readonly logger = new NLogLogger(typeof(MyClass));
public void DoSomething()
{
logger.Info("Hello from DoSomething");
}
}
Or you could inject the logger into your class.