Providing complete Serilog Elasticsearch boilerplate
The solution includes Program.cs with Serilog configured from appsettings.json, middleware capturing a correlation ID from request headers (or generating one), pushing it into Serilog’s LogContext for enriched logging, and a sample WeatherForecastController; appsettings.json configures Serilog to write structured logs to Elasticsearch and console with enrichers for machine and thread information.
Below is a minimal ASP.NET Core Web API boilerplate using Serilog for structured logging, configured with an Elasticsearch sink. It also includes middleware to capture a correlation ID from incoming request headers (or generate one) and push it into the log scope for distributed tracing.
1) Program.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Context;
var builder = WebApplication.CreateBuilder(args);
// Configure Serilog from appsettings.json
builder.Host.UseSerilog((context, services, configuration) =>
{
configuration
.ReadFrom.Configuration(context.Configuration)
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.Enrich.WithProcessId()
.Enrich.WithThreadId();
});
builder.Services.AddControllers();
var app = builder.Build();
// Add the correlation ID middleware
app.UseMiddleware<CorrelationIdMiddleware>();
// Optional: Serilog request logging middleware
app.UseSerilogRequestLogging(options =>
{
// Customize the message template to include correlation ID if desired
options.MessageTemplate = "Handled {RequestPath}";
});
app.MapControllers();
app.Run();
2) CorrelationIdMiddleware.cs
using Microsoft.AspNetCore.Http;
using Serilog.Context;
using System;
using System.Linq;
using System.Threading.Tasks;
public class CorrelationIdMiddleware
{
private const string CorrelationIdHeader = "X-Correlation-ID";
private readonly RequestDelegate _next;
public CorrelationIdMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
// Get correlation ID from header, or generate a new one
var correlationId = context.Request.Headers[CorrelationIdHeader].FirstOrDefault();
if (string.IsNullOrWhiteSpace(correlationId))
{
correlationId = Guid.NewGuid().ToString();
}
// Set it on the response headers so downstream services/clients can use it
context.Response.Headers[CorrelationIdHeader] = correlationId;
// Optionally set HttpContext.TraceIdentifier to keep it in sync
context.TraceIdentifier = correlationId;
// Push the correlation ID into the Serilog LogContext
using (LogContext.PushProperty("CorrelationId", correlationId))
{
await _next(context);
}
}
}
3) Example Controller
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IActionResult Get()
{
_logger.LogInformation("Processing WeatherForecast request at {Time}", DateTimeOffset.UtcNow);
return Ok(new { Forecast = "Sunny", CorrelationId = HttpContext.TraceIdentifier });
}
}
4) appsettings.json (Serilog config with Elasticsearch sink)
{
"Serilog": {
"Using": [ "Serilog.Sinks.Elasticsearch" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{ "Name": "Console" },
{
"Name": "Elasticsearch",
"Args": {
"nodeUris": "http://localhost:9200",
"indexFormat": "myapp-logs-{0:yyyy.MM.dd}",
"autoRegisterTemplate": true,
"autoRegisterTemplateVersion": "ESv7",
"typeName": "_doc" // ignored in 7.x/8.x but allowed
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "MyApp"
}
}
}
5) Required NuGet Packages
dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.Elasticsearch
How it works:
- The
CorrelationIdMiddleware checks the X-Correlation-ID header; if missing, it generates one.
- It sets the correlation ID on the response headers and on
HttpContext.TraceIdentifier.
LogContext.PushProperty("CorrelationId", correlationId) ensures every log within that request scope carries the correlation ID.
Enrich.FromLogContext() in the Serilog configuration picks up CorrelationId (and any other pushed properties) so they’re included in structured logs and sent to Elasticsearch.