So, my question is what is the proper way to create implementation that proxies to Serilog?
you should create something like:
public class SerilogAdapter : ILogger
{
private readonly Serilog.ILogger m_Adaptee;
public SerilogAdapter(Serilog.ILogger adaptee)
{
m_Adaptee = adaptee;
}
public void Log(LogEntry entry)
{
if (entry.Severity == LoggingEventType.Debug)
m_Adaptee.Debug(entry.Exception, entry.Message);
if (entry.Severity == LoggingEventType.Information)
m_Adaptee.Information(entry.Exception, entry.Message);
else if (entry.Severity == LoggingEventType.Warning)
m_Adaptee.Warning(entry.Message, entry.Exception);
else if (entry.Severity == LoggingEventType.Error)
m_Adaptee.Error(entry.Message, entry.Exception);
else
m_Adaptee.Fatal(entry.Message, entry.Exception);
}
}
Does that mean that every class that will log sth (so basically every), should have ILogger in its constructor?
As I understand from Stevens answer: Yes, you should do this.
what is the best way to use it later in the code?
If you are using a DI container, then just use the DI container to map ILogger
to SerilogAdapter
. You also need to register Serilog.ILogger
, or just give an instance of Serilog logger to the DI container to inject it to the SerilogAdapter constructor.
If you don't use a DI container, i.e., you use Pure DI, then you do something like this:
Serilog.ILogger log = Serilog.Log.Logger.ForContext("MyClass");
ILogger logging_adapter = new SerilogAdapter(log);
var myobject = new MyClass(other_dependencies_here, logging_adapter);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…