I have a base class and using nlog logging. In my base class I have a method that gets passed in a logger object and then logs it to that logger.
When it logs it, logs it as the base class, I was hoping it would use the child class name.
<logger name="Uploads" minlevel="Debug" writeTo="Uploads" />
public void Child : Parent
{
private readonly Logger logger = LogManager.GetLogger("Uploads")
public void ParentMethod(Logger logger)
{
logger.Info("hi");
}
}
You may use ${callsite}
in the layout
to determine the format of log message.
layout="${longdate}|${level:uppercase=true}|${callsite:includeNamespace=false:className=true:fileName=false:includeSourcePath=false:methodName=false}|${message}"
This will log messages in following format:
2018-03-15 18:11:43.1173|TRACE|{className}|{message}
The short answer is the NLog team considers this a breaking change so it hasn't been resolved yet. However, there are a couple workarounds that might work.
Name the logger explicitly for each child class using GetType() and the Name
property and pass it to GetLogger :
var logger = LogManager.GetLogger(GetType().Name);
Create a custom sub-class logger .
Add to the base class custom logging methods that automatically add the child class name using GetType().Name along with the message. Below is some example pseudocode:
public class BaseClass
{
protected Logger logger = LogManager.GetLogger("BaseClass");
protected void LogError(string message)
{
logger.Error($"{GetType().Name}: {message}");
}
protected void LogInfo(string message)
{
logger.Info($"{GetType().Name}: {message}");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.