logging
Skill5 starsChanged 6 days agoMITView on GitHub
Serilog structured logging for ASP.NET Core — setup, message templates, LogContext enrichment, request logging middleware, and log level guidelines.
25 other projects use a version of this.
Adopted by
Most recently taken up by
- codewithmukesh/dotnet-claude-kittheir own version, first seen Nov 8, 2026
- lawless-m/claude-skillstheir own version, first seen Nov 6, 2026
- gabrielbauman/skillstheir own version, first seen Nov 1, 2026
- jars-demo/jars-skillstheir own version, first seen Oct 25, 2026
- andr-ca/agentharnesstheir own version, first seen Oct 15, 2026
- syntropic137/software-leverage-pointstheir own version, first seen Oct 14, 2026
Used with
Projects with it also use configuration, dependency-injection and 3 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
junhjangSkillconfiguration
Adding a new config file, adding a field, or wiring a config consumer. Enforces schema validation at startup (no permissive defaults), env-var indirection for secrets, layered config (defaults / per-env / operator-override), hot-reload explicit per field.
Also in 4 projects that use this
HamzaSheikh768Skilldependency-injection
Leverages FastAPI's powerful Depends system for reusable authentication, database sessions, rate limiting, and business logic injection.
Also in 4 projects that use this
wpankSkillapi-versioning
API versioning strategies — URL path, header, query param, content negotiation — with breaking change classification, deprecation timelines, migration patterns, and multi-version support. Use when evolving APIs, planning breaking changes, or managing version lifecycles.
Also in 3 projects that use this
dbtlrSkilldependencies
Use when adding, evaluating, or updating Rust crate dependencies. Also use when considering whether to implement something yourself vs pulling in a library.
Also in 3 projects that use this
lukevellaSkillbetter-auth-security-best-practices
This skill provides guidance for implementing security features that span across Better Auth, including rate limiting, CSRF protection, session security, trusted origins, secret management, OAuth security, IP tracking, and security auditing. These topics are not covered in individual plugin skills.
Also in 3 projects that use this
Other versions25 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 25
- elie222/inbox-zero★ 13ksame name
- lukevella/rallly★ 5.4ksame name
- epicenter-md/epicenter★ 4.8ksame name
- EpicenterHQ/epicenter★ 4.8ksame name
- golemcloud/golem★ 1.5ksame name
- codewithmukesh/dotnet-claude-kit★ 808same name
- emavgl/oinkoin★ 486same name
- QuantConnect/Documentation★ 268same name
- Resgrid/Core★ 238same name
- lawless-m/claude-skills★ 6same name
15 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository15 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- aspnet-api-patternsSkill
- authenticationSkill
- cachingSkill
- clean-architectureSkill
- convention-learnerSkill
- dddSkill
- dotnet-project-initSkill
- ef-core-patternsSkill
- error-handlingSkill
- modern-csharpSkill
- opentelemetrySkill
- resilienceSkill
- testing-dotnetSkill
- vertical-sliceSkill
The file
We split this skill into the rules it gives an agent
2 rules. 0 are common, 1 is distinctive, and 1 is very specific to this project.
0
Common
Most of the 20 edited versions we read keep these.
1
Distinctive
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 81
Always use message templates, never string interpolation.
- Very specific: line 161
Avoid building expensive log messages that may not be written.
“Common” is measured: kept by at least 6 in 10 of the 20 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Serilog Structured Logging
Reference material for adding and using Serilog in ASP.NET Core.
NuGet Packages
<PackageReference Include="Serilog.AspNetCore" Version="8.*" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="3.*" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="4.*" />
<PackageReference Include="Serilog.Formatting.Compact" Version="3.*" />
<!-- Add sinks as needed: -->
<PackageReference Include="Serilog.Sinks.OpenTelemetry" Version="4.*" />Setup — Program.cs
Replace the default ASP.NET Core logging before builder.Build():
builder.Host.UseSerilog((context, config) =>
config
.ReadFrom.Configuration(context.Configuration)
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.Enrich.WithThreadId()
.WriteTo.Console(new CompactJsonFormatter())
.WriteTo.OpenTelemetry()); // swap/add sinks as neededFor early startup errors, bootstrap a minimal logger before the host is built:
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateBootstrapLogger();
try
{
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog((ctx, cfg) => cfg.ReadFrom.Configuration(ctx.Configuration)...);
// ...
}
catch (Exception ex)
{
Log.Fatal(ex, "Application startup failed.");
}
finally
{
Log.CloseAndFlush();
}appsettings.json Configuration
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"Microsoft.EntityFrameworkCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning",
"System": "Warning"
}
}
}
}Flip EF Core's Database.Command override to Information temporarily when debugging query issues; revert before shipping.
Structured Logging — Message Templates
Always use message templates, never string interpolation. Interpolation loses the structured property; templates capture it.
// CORRECT — structured properties captured
_logger.LogInformation("Order {OrderId} created for customer {CustomerId}", order.Id, order.CustomerId);
_logger.LogWarning("Payment failed for order {OrderId}: {Reason}", orderId, reason);
_logger.LogError(ex, "Failed to process order {OrderId}", orderId);
// WRONG — interpolated string loses structure, all you get is text
_logger.LogInformation($"Order {order.Id} created for customer {order.CustomerId}");Naming convention for template properties: PascalCase, noun-first (OrderId, not id).
LogContext Enrichment
Push properties onto the log context to include them in every log line emitted within a scope. Useful for request-scoped IDs.
using (LogContext.PushProperty("UserId", userId))
using (LogContext.PushProperty("RequestId", httpContext.TraceIdentifier))
{
await ProcessOrderAsync(orderId, ct);
}In middleware, enrich once per request:
public class UserContextMiddleware(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext context)
{
var userId = context.User.FindFirstValue("sub");
if (userId is not null)
using (LogContext.PushProperty("UserId", userId))
{
await next(context);
return;
}
await next(context);
}
}Request Logging Middleware
Replace ASP.NET Core's default request logging with Serilog's, which emits one structured line per request:
// In Program.cs — place before UseRouting/UseAuthentication
app.UseSerilogRequestLogging(options =>
{
options.MessageTemplate =
"HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms";
options.GetLevel = (ctx, elapsed, ex) =>
ex is not null || ctx.Response.StatusCode >= 500
? LogEventLevel.Error
: LogEventLevel.Information;
options.EnrichDiagnosticContext = (diagCtx, httpContext) =>
{
diagCtx.Set("UserId", httpContext.User.FindFirstValue("sub"));
diagCtx.Set("ClientIp", httpContext.Connection.RemoteIpAddress?.ToString());
};
});Log Level Guidelines
| Level | When to use | Production default |
Verbose / Trace | SQL queries, cache hits, per-frame loops | Off |
Debug | Detailed flow for diagnosing a specific issue | Off |
Information | Business events (order created, user logged in, job started) | On |
Warning | Recoverable issues: retry attempt, cache miss storm, deprecated API call; request validation failures (a client error, not a fault) | On |
Error | Failures affecting one request that the service caused or could not absorb: DB timeout, unhandled exception, downstream outage | On |
Fatal | Application cannot continue: startup failure, unrecoverable state | On |
Performance Guard
Avoid building expensive log messages that may not be written. Use the IsEnabled guard:
if (_logger.IsEnabled(LogLevel.Debug))
{
var payload = JsonSerializer.Serialize(largeObject);
_logger.LogDebug("Full request payload: {Payload}", payload);
}For hot paths, use the [LoggerMessage] source generator — it emits the IsEnabled check and avoids
boxing. It takes MEL's LogLevel, not Serilog's LogEventLevel:
internal static partial class OrderLog
{
[LoggerMessage(EventId = 1, Level = LogLevel.Information, Message = "Order {OrderId} created.")]
public static partial void OrderCreated(ILogger logger, Guid orderId);
}
OrderLog.OrderCreated(_logger, order.Id);Security Rules
Never log:
- Passwords, PINs, security questions
- Auth tokens, API keys, session IDs
- PII: email addresses, names, SSNs, credit card numbers, phone numbers
- Full request bodies containing any of the above
Redact at source — don't rely on log pipeline filtering:
// WRONG
_logger.LogInformation("User login attempt: {Email} / {Password}", email, password);
// CORRECT
_logger.LogInformation("User login attempt for account {AccountId}", accountId);See Also
skills/opentelemetry/SKILL.md— trace/span setup and log↔trace correlation (TraceId/SpanId)
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

