When using Serilog, contextual loggers attach the logging type's name to log events so they can later be found and filtered:
var log = Log.ForContext<SomeClass>();
log.Information("This event is tagged with 'SomeClass'");
Applications that use IoC often accept dependencies as constructor parameters:
public class SomeClass
{
readonly ILogger _log;
public SomeClass(ILogger log)
{
_log = log;
}
public void Show()
{
_log.Information("This is also an event from 'SomeClass'");
}
}
This library configures Autofac to automatically configure the correct contextual logger for each class into which an ILogger
is injected.
First install from NuGet:
Install-Package AutofacSerilogIntegration
Next, create the root logger:
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
Then when configuring the Autofac container, call RegisterLogger()
:
var builder = new ContainerBuilder();
builder.RegisterLogger();
If no logger is explicitly passed to this function, the default Log.Logger
will be used.