agentleFS
zdanovichnickzdanovichnick/dotnet-pilot/skills/logging/SKILL.md

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

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.
  • junhjangSkill

    configuration

    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

  • HamzaSheikh768Skill

    dependency-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

  • wpankSkill

    api-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

  • dbtlrSkill

    dependencies

    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

  • lukevellaSkill

    better-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

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
  1. Distinctive:

    Always use message templates, never string interpolation.

    line 81
  2. Very specific:

    Avoid building expensive log messages that may not be written.

    line 161

“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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

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 needed

For 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

LevelWhen to useProduction default
Verbose / TraceSQL queries, cache hits, per-frame loopsOff
DebugDetailed flow for diagnosing a specific issueOff
InformationBusiness events (order created, user logged in, job started)On
WarningRecoverable issues: retry attempt, cache miss storm, deprecated API call; request validation failures (a client error, not a fault)On
ErrorFailures affecting one request that the service caused or could not absorb: DB timeout, unhandled exception, downstream outageOn
FatalApplication cannot continue: startup failure, unrecoverable stateOn

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)

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.