- .Net Core Serilog – Basic
- .Net Core Serilog – Configuration
- .Net Core Serilog - Structured JSON output
- .Net Core Serilog - Enrichers
- .Net Core Serilog - Custom JSON output
- .Net Core Serilog - Adding Sinks
This is part 1 of 6.
Serilog isn't too hard to setup, but the following outlines the simplest steps (that I have found) to add Serilog to a .Net Core Web API project:
- Create a new a ASP.NET Core Web Application and select API. (Weather API Sample)
- Change the Get() method in WeatherForcastController.cs to the following:
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var cnt = 10;
var minTemp = -20;
var maxTemp = 55;
_logger.LogInformation("===> Get was called <=== Count: {Count}, MinTemp: {MinTemp}, MaxTemp: {MaxTemp}", cnt, minTemp, maxTemp);
var rng = new Random();
return Enumerable.Range(1, cnt).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(minTemp, maxTemp),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
- Run the app (without Serilog), you should see the default logging implementation at the command line.
- Now add the “Serilog.AspNetCore” NuGet package to your project.
- In Program.cs, add “using Serilog;” to the top of the file and change the CreateHostBuilder() method to the following:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
.WriteTo.Console()
);
- In the Startup.cs file, add the following, before app.UseEndpoints() near the bottom of the file.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseSerilogRequestLogging(); // <-- Add this
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}