Reputation: 2879
I'm developing console .Net application and use Nlog for logging. I use ${callsite} layout template for logging class name. I want to see in log file the name of inherited class when it called from parent
example:
using NLog;
namespace ConsoleApp17
{
internal class Program
{
private static void Main(string[] args)
{
var a = new MyClass2();
a.Do1();
a.Do2();
a.Do3();
}
public class MyClass
{
protected virtual Logger Logger { get; } = null;
public void Do1()
{
Logger.Info("Do1");
}
public virtual void Do2()
{
Logger.Info("Do2");
}
}
public class MyClass2 : MyClass
{
protected override Logger Logger { get; } = LogManager.GetCurrentClassLogger();
public override void Do2()
{
Logger.Info("Do22");
}
public void Do3()
{
Logger.Info("Do3");
}
}
}
}
log is:
2017-05-18 18:22:02.7761|1|ConsoleApp17.Program+MyClass.Do1|INFO|Do1|
2017-05-18 18:22:02.8611|1|ConsoleApp17.Program+MyClass2.Do2|INFO|Do22|
2017-05-18 18:22:04.2831|1|ConsoleApp17.Program+MyClass2.Do3|INFO|Do3|
U see, that in lines 2 and 3 there is an inherited class name MyClass2, but in line 1 there is a parent class name MyClass.
How can i achieve writing to log an inherited class name when it's called from parent?
Upvotes: 0
Views: 1038
Reputation: 46
You can use ${logger}
template instead of ${callsite}
.
When used together with GetCurrentClassLogger()
, it will show the name of the object type that created the logger. In your case it will be MyClass2
.
Upvotes: 3