There is an answer here: How do I pass a dependency to a Serilog Enricher? which explains you can pass an instance in.
However to do that I would need to move my logger setup after my dependency injection code has ran (in the startup.cs
)
This means that startup errors won't be logged because the logger won't be ready yet.
Is there a way to somehow configure serilog to run in my Main()
method, but also enrich data with a DI item? The DI item has further dependencies (mainly on database connection) although it is a singleton.
I've googled this and read something about adding things to a context, but I've been unable to find a complete working example that I can adapt.
Most of the examples I've found involve putting code into the controller to attach information, but I want this to be globally available for every single log entry.
My Main starts with :
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(elasticUri))
{
AutoRegisterTemplate = true,
})
.CreateLogger();
Before going into the .NET Core MVC code
CreateWebHostBuilder(args).Build().Run();
My DI object is basically a "UserData" class that contains username, companyid, etc. which are properties that hit the database when accessed to get the values based on some current identity (hasn't been implemented yet). It's registered as a singleton by my DI.
Structured Logging with Serilog. To enable structured logging with the File Sink, we need to add a JSON formatter as a Parameter to the Settings. Let's add new Sink to our appSettings. json/Serilog. Add the below code as the sink.
Log Context enricher - Built in to Serilog, this enricher ensures any properties added to the Log Context are pushed into log events. Environment enrichers - Enrich logs with the machine or current user name.
I would suggest using a simple middleware that you insert in the ASP .NET Core pipeline, to enrich Serilog's LogContext with the data you want, using the dependencies that you need, letting the ASP .NET Core dependency injection resolve the dependencies for you...
e.g. Assuming IUserDataService
is a service that you can use to get the data you need, to enrich the log, the middleware would look something like this:
public class UserDataLoggingMiddleware
{
private readonly RequestDelegate _next;
public UserDataLoggingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context, IUserDataService userDataService)
{
var userData = await userDataService.GetAsync();
// Add user data to logging context
using (LogContext.PushProperty("UserData", userData))
{
await _next.Invoke(context);
}
}
}
LogContext.PushProperty
above is doing the enrichment, adding a property called UserData
to the log context of the current execution.
ASP .NET Core takes care of resolving IUserDataService
as long as you registered it in your Startup.ConfigureServices
.
Of course, for this to work, you'll have to:
1. Tell Serilog to enrich the log from the Log context, by calling Enrich.FromLogContext()
. e.g.
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration)
.Enrich.FromLogContext() // <<======================
.WriteTo.Console(
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} " +
"{Properties:j}{NewLine}{Exception}")
.CreateLogger();
2. Add your middleware to the pipeline, in your Startup.Configure
. e.g.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// ...
app.UseMiddleware<UserDataLoggingMiddleware>();
// ...
app.UseMvc();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With