For some reason, I find it very hard to understand what's going on with Serilog configuration. I have a web api with .NET Core 2.1 and installed serilog.sink.logstash
. My startup has:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
var serverURL = Configuration.GetSection("Logging")["logstashServer"];
var logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithProperty("Enviroment", env.EnvironmentName)
.Enrich.WithProperty("ApplicationName", "MyApp")
.WriteTo.LogstashHttp(serverURL);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
logger.WriteTo.Console();
}
loggerFactory.AddSerilog();
Log.Logger = logger.CreateLogger();
app.UseCors("CorsPolicy");
app.UseMvc();
}
My appsettings has a section:
"Logging": {
"logstashServer": "http://192.168.0.6:8101",
"IncludeScopes": false,
"Serilog": {
"MinimumLevel": {
"Default": "Error",
"Override": {
"Microsoft": "Error",
"Microsoft.AspNetCore.Hosting": "Error",
"Microsoft.AspNetCore.Mvc": "Error",
"System": "Error"
}
}
}
}
No matter what I do, I see both in console and logstash than a lot of unwanted information is logged like:
[14:27:54 INF] Executed action method MyApp.Controllers.LoggerController.Post (MyApp), returned result Microsoft.AspNetCore.Mvc.OkResult in 0.0771ms.
MyApp> [14:27:54 INF] Executing HttpStatusCodeResult, setting HTTP status code 200
MyApp> [14:27:54 INF] Executed action MyApp.Controllers.LoggerController.Post (MyApp) in 2.0855ms
and so on. Why do I see those since I have minimum level error?
Although you've added configuration to appsettings.json
for overriding the Serilog logging levels, you've not actually passed said configuration into Serilog. At the simplest level, this requires you to install the Serilog.Settings.Configuration nuget package. Once you've done that, you can add a call to ReadFrom.Configuration
, like so:
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration.GetSection("Logging"))
.Enrich.FromLogContext()
// ...
This is all you need in order to get your configuration into Serilog, but you do have other issues with how you're still using ILoggerFactory
inside of Configure
(this changed in ASP.NET Core 2.0). One of the issues this is likely causing for you is that both ASP.NET Core's Console provider and the Serilog Console sink are writing logs. If you need help with any of that, it's well documented online, but of course you can create additional Stack Overflow questions if absolutely necessary.
Nicholas Blumhardt blogged about the ASP.NET Core 2.0 logging changes - This is a useful read that should help simplify your Serilog + ASP.NET Core experience greatly.