NLog & Serilog Structured Logging in .NET: Production nlog.config & JSON Pipelines
Table of Contents (4 min read)
Structured Logging in .NET: Enterprise nlog.config & Modern JSON Sinks
In enterprise systems engineering, logs are not merely text messages printed to a console; they are structured time-series events that represent the pulse of your distributed application. When troubleshooting production microservices, payment gateways, or background workers across Windows Server and Debian Linux containers, structured logging makes the difference between resolving an incident in minutes or spending hours parsing unformatted text files.
In the C# and .NET ecosystem, NLog has long stood as an industry-standard logging provider, renowned for its asynchronous targets, flexible XML routing, and minimal garbage collection overhead. In modern cloud-native architectures like our DenverNerd .NET 9 Minimal APIs engine, NLog patterns seamlessly bridge into Serilog structured JSON sinks.
1. Production nlog.config Template
Below is our battle-tested nlog.config template, designed for high-throughput ASP.NET Core web services. It includes asynchronous non-blocking file writers, rolling daily log archives, colored console output for local debugging, and structured JSON layout formatting:
<?xml version="1.0" encoding="utf-8" ?>
<!-- https://github.com/NLog/NLog/wiki/Configuration-file -->
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogFile="${basedir}/logs/log-internal.log"
throwConfigExceptions="true"
internalLogLevel="Off">
<variable name="logDirectory" value="${basedir}/logs" />
<!-- Enable asynchronous non-blocking logging thread -->
<targets async="true">
<!-- Visual Studio Debug Console Target -->
<target name="debugger" xsi:type="Debugger"
layout="${time:format=HH:mm:ss.fff}|${level:uppercase=true:padding=-5}|${threadid:padding=-2}|${logger}|${message}" />
<!-- High-Performance Colored Console Target -->
<target xsi:type="ColoredConsole" name="coloredConsole"
layout="${date:format=yyyy-MM-dd HH\:mm\:ss.fff} [${level:uppercase=true:padding=-5}] (${logger:shortName=true}) ${message} ${exception:format=tostring}"
useDefaultRowHighlightingRules="true">
<highlight-row condition="level == LogLevel.Trace" foregroundColor="DarkGray" />
<highlight-row condition="level == LogLevel.Debug" foregroundColor="Yellow" />
<highlight-row condition="level == LogLevel.Info" foregroundColor="White" />
<highlight-row condition="level == LogLevel.Warn" foregroundColor="Magenta" />
<highlight-row condition="level == LogLevel.Error" foregroundColor="Red" />
<highlight-row condition="level == LogLevel.Fatal" foregroundColor="Red" backgroundColor="White" />
</target>
<!-- Structured JSON File Target (Logstash / Vector / Seq Ingest) -->
<target xsi:type="File" name="jsonFile"
fileName="${logDirectory}/app-json-${shortdate}.log"
archiveFileName="${logDirectory}/archives/app-json.{#}.log"
archiveNumbering="DateAndSequence"
archiveDateFormat="yyyy-MM-dd"
archiveAboveSize="52428800"
maxArchiveFiles="14">
<layout xsi:type="JsonLayout" includeAllProperties="true">
<attribute name="timestamp" layout="${date:format=o}" />
<attribute name="level" layout="${level:upperCase=true}" />
<attribute name="logger" layout="${logger}" />
<attribute name="correlationId" layout="${mdlc:item=CorrelationId}" />
<attribute name="message" layout="${message}" />
<attribute name="exception" layout="${exception:format=toString,StackTrace}" encode="false" />
</layout>
</target>
<!-- Standard Rolling Text Target for System Administrators -->
<target xsi:type="File" name="allFile"
fileName="${logDirectory}/app-all-${shortdate}.log"
archiveFileName="${logDirectory}/archives/app-all.{#}.log"
archiveNumbering="Rolling"
archiveEvery="Day"
maxArchiveFiles="7"
layout="${longdate}|${event-properties:item=EventId:whenEmpty=0}|${level:uppercase=true:padding=-5}|${logger}|${message} ${exception:format=tostring}" />
<!-- Blackhole target for dropping noisy framework telemetry -->
<target xsi:type="Null" name="blackhole" />
</targets>
<rules>
<!-- Log startup lifetime events to console -->
<logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="coloredConsole" final="true" />
<!-- Suppress verbose Microsoft EF Core and Kestrel hosting logs from disk files -->
<logger name="Microsoft.*" minlevel="Trace" maxlevel="Info" writeTo="blackhole" final="true" />
<logger name="System.Net.Http.*" minlevel="Trace" maxlevel="Info" writeTo="blackhole" final="true" />
<!-- Application-level logging routes -->
<logger name="*" minlevel="Debug" writeTo="coloredConsole" />
<logger name="*" minlevel="Info" writeTo="allFile,jsonFile" />
</rules>
</nlog>
2. Bootstrapping NLog in ASP.NET Core (Program.cs)
To wire NLog into the ASP.NET Core dependency injection container:
using NLog;
using NLog.Web;
var logger = LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
logger.Debug("Bootstrapping .NET runtime host...");
try
{
var builder = WebApplication.CreateBuilder(args);
// Replace default logging with NLog
builder.Logging.ClearProviders();
builder.Host.UseNLog();
var app = builder.Build();
app.MapGet("/healthz", () => Results.Ok(new { status = "Healthy" }));
app.Run();
}
catch (Exception ex)
{
logger.Fatal(ex, "Application terminated unexpectedly during bootstrap.");
throw;
}
finally
{
LogManager.Shutdown();
}
3. The Evolution: Transitioning to Serilog in .NET 9
While NLog remains a reliable choice for XML-configured workloads, the DenverNerd .NET 9 Minimal APIs engine utilizes Serilog for compact, native JSON formatting and distributed tracing.
Here is how we configure Serilog with structured JSON sinks, correlation IDs, and dynamic log level filtering:
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
.Enrich.FromLogContext()
.Enrich.WithProperty("Service", "DenverNerd.Api")
.Enrich.WithProperty("Environment", builder.Environment.EnvironmentName)
.WriteTo.Console(
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} <{CorrelationId}>{NewLine}{Exception}")
.WriteTo.File(
new CompactJsonFormatter(),
path: "logs/denvernerd-.json",
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 14)
.CreateLogger();
builder.Host.UseSerilog();
Correlation ID Middleware
In distributed architectures, passing a unique trace identifier across reverse proxies (Caddy, Cloudflare) and microservices is paramount. With Serilog or NLog, capture the X-Correlation-ID header and push it to the logging context:
app.Use(async (context, next) =>
{
string correlationId = context.Request.Headers["X-Correlation-ID"].FirstOrDefault()
?? Guid.NewGuid().ToString("D");
context.Response.Headers["X-Correlation-ID"] = correlationId;
using (LogContext.PushProperty("CorrelationId", correlationId))
{
await next();
}
});
4. Best Practices for Production Logging
- Always Use Asynchronous Targets (
async="true"): Synchronous file writes block application request threads during disk I/O spikes. - Implement Retention Lifecycles: Uncapped log files inevitably fill OS partitions, causing server crashes. Maintain strict daily rotations with a 7 to 14-day retention ceiling.
- Blackhole Framework Noise: Never log EF Core queries or raw socket handshakes at
Debuglevel to disk in production. - Log Events, Not Raw Strings: Use structured message templates (
logger.LogInformation("Order {OrderId} processed for {CustomerEmail}", order.Id, email)) rather than string interpolation ($"Order {order.Id}...") to retain queryable metadata attributes in Seq, OpenSearch, and Datadog.
Discussion (0)
Community Guidelines EnforcedNo community comments yet. Be the first to share your thoughts!
Join the Community Discussion
Sign in or create an account to share observations, tuning setups, and connect with other makers.