跳到正文
FunCoding

logging

Logging for .NET 10: ILogger message templates, [LoggerMessage] source generation, Serilog (references/serilog.md), health check endpoints, correlation IDs, log levels. Use for "ILogger", "Serilog", "structured logging", "LoggerMessage", "Seq", "correlation ID", "health checks". Do NOT use for traces, metrics or OTLP SDK setup (use opentelemetry) or retry and circuit-breaker policies (use resilience).

Star
856
许可证
MIT
最近提交
2026年11月29日

skills/logging/SKILL.md

在 GitHub 上查看

Logging & Observability

Core Principles

  1. ILogger<T> is the API, Serilog is the provider — Application code depends only on Microsoft.Extensions.Logging. Serilog plugs in underneath for sinks, enrichment, and configuration. Swapping the provider never touches call sites.
  2. Structured events, never formatted strings — {OrderId} in a message template creates a queryable property. String interpolation destroys that structure and allocates even when the level is off.
  3. [LoggerMessage] on hot paths and shared messages — The source generator emits the delegate at compile time: no boxing, no template parsing, zero allocations when the level is disabled.
  4. Health checks answer two questions — Liveness ("restart me?") and readiness ("send traffic?") are separate endpoints. Conflating them turns a slow database into a restart loop.
  5. One correlation ID per request — Push it once at the pipeline edge so every log line, and every outgoing call, carries it.

Traces and metrics belong to the opentelemetry skill. Wire logging first (you need logs to debug the rest), then health checks, then tracing.

Patterns

Serilog Setup (Minimal)

using Serilog;

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .CreateBootstrapLogger();          // captures startup failures

try
{
    var builder = WebApplication.CreateBuilder(args);

    builder.Services.AddSerilog((services, lc) => lc
        .ReadFrom.Configuration(builder.Configuration)
        .ReadFrom.Services(services)
        .Enrich.FromLogContext());

    var app = builder.Build();
    app.UseSerilogRequestLogging();    // one summary event per request
    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
    await Log.CloseAndFlushAsync();    // flush async sinks (Seq, OTLP)
}

Why: the bootstrap logger records failures that happen before DI is built. AddSerilog() (not the legacy UseSerilog()) lets the logger resolve services through ReadFrom.Services. Levels, sinks, and overrides live in appsettings.json so they change per environment without a redeploy. Full configuration, sinks, enrichers, destructuring, and filtering are in references/serilog.md.

Message Templates and Source-Generated Logging

// Ad-hoc: named placeholders keep the properties queryable
logger.LogInformation("Order {OrderId} placed by {CustomerId}", orderId, customerId);

// Hot paths and messages reused in several places
public static partial class OrderLogs
{
    [LoggerMessage(Level = LogLevel.Information,
        Message = "Order {OrderId} created for {CustomerId}")]
    public static partial void OrderCreated(this ILogger logger, Guid orderId, Guid customerId);
}

logger.OrderCreated(order.Id, order.CustomerId);

Why: the generated method checks IsEnabled first, so a disabled level costs one branch. A named method also gives each event a stable ID and wording, which makes alerts reliable.

Correlation IDs

using Serilog.Context;

internal sealed class CorrelationIdMiddleware(RequestDelegate next)
{
    private const string Header = "X-Correlation-Id";

    public async Task InvokeAsync(HttpContext context)
    {
        var correlationId = context.Request.Headers[Header].FirstOrDefault()
            ?? Guid.NewGuid().ToString("N");

        context.Response.Headers[Header] = correlationId;

        using (LogContext.PushProperty("CorrelationId", correlationId))
        {
            await next(context);
        }
    }
}

// Program.cs: register early so every downstream log carries the ID
app.UseMiddleware<CorrelationIdMiddleware>();

Why middleware: the property is pushed once and attaches to every event in the request scope, with no per-call-site plumbing. LogContext needs .Enrich.FromLogContext(). Forward the same header on outgoing HttpClient calls with a DelegatingHandler (see httpclient-factory). Without Serilog, logger.BeginScope(new Dictionary<string, object> { ["CorrelationId"] = id }) does the same job.

Health Checks

using Microsoft.AspNetCore.Diagnostics.HealthChecks;

builder.Services.AddHealthChecks()
    .AddNpgSql(builder.Configuration.GetConnectionString("Default")!,
        name: "database", tags: ["ready"])
    .AddRedis(builder.Configuration.GetConnectionString("Redis")!,
        name: "redis", tags: ["ready"]);

app.MapHealthChecks("/health/live", new HealthCheckOptions
{
    Predicate = _ => false             // no dependency checks: "am I running?"
}).AllowAnonymous();

app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("ready")
}).AllowAnonymous();

Why two endpoints: liveness failing means "restart me"; readiness failing means "stop sending traffic". Probes come from load balancers and orchestrators, so mark them AllowAnonymous() explicitly. Check package availability with dotnet add package, never pin versions from memory.

Log-Level Strategy

LevelUse forWhere enabled
DebugDiagnostic detail, payload dumpsDevelopment only
InformationBusiness events: order placed, job completedDev and staging; production via namespace overrides
WarningRecoverable anomalies: retry fired, fallback usedEverywhere, production default
ErrorFailed operations needing attentionEverywhere
CriticalApp cannot continueEverywhere

Why Warning as the production default: framework Information noise at scale costs real money in storage and buries signals. Raise your own namespaces to Information with MinimumLevel.Override (see references/serilog.md). Use TimeProvider, not DateTime.Now, when a log message needs a timestamp you compute yourself; sinks already stamp events.

Anti-patterns

String Interpolation in Log Calls

// BAD: breaks structure, allocates even when the level is disabled
logger.LogInformation($"Order {orderId} created for {customerId}");

// GOOD: message template with named parameters
logger.LogInformation("Order {OrderId} created for {CustomerId}", orderId, customerId);

Logging Sensitive Data

// BAD: credentials and PII in logs
logger.LogInformation("Login: {Email} with password {Password}", email, password);

// GOOD: identifiers only; emails, names, IPs, and tokens stay at Debug in development
logger.LogInformation("User {UserId} logged in", userId);

One Endpoint for Every Probe

// BAD: all checks run for liveness AND readiness
app.MapHealthChecks("/health");

// GOOD: separate liveness from readiness
app.MapHealthChecks("/health/live", new() { Predicate = _ => false });
app.MapHealthChecks("/health/ready", new() { Predicate = c => c.Tags.Contains("ready") });

Skipping CloseAndFlush

// BAD: buffered events from async sinks are lost on exit
app.Run();

// GOOD: flush in finally (see Serilog Setup above)
finally { await Log.CloseAndFlushAsync(); }

Static Serilog Log.* Calls in Application Code

// BAD: hidden static dependency, bypasses DI, hard to test
Log.Information("Order {OrderId} created", orderId);

// GOOD: inject ILogger<T>; keep Log.* for Program.cs bootstrap only
public sealed class OrderService(ILogger<OrderService> logger) { }

Decision Guide

ScenarioRecommendation
Application loggingILogger<T> + Serilog via AddSerilog() and appsettings
Hot path or reused message[LoggerMessage] source generator
Sinks, enrichers, destructuring, filteringreferences/serilog.md
Request loggingUseSerilogRequestLogging()
Request tracing across servicesCorrelation ID middleware plus OpenTelemetry
Scoped properties (tenant, user)LogContext.PushProperty() in middleware
Distributed tracing, metrics, OTLPopentelemetry skill
Container health/health/live and /health/ready, probed by the orchestrator
Log storageSeq or Aspire dashboard for development; OTLP backend or Elastic for production
Audit trailSerilog AuditTo (synchronous, failures propagate)

相似的 Skill

精选

internal-comms

写内部沟通文档,遵循公司格式,包括状态报告、领导更新和公司通讯。

ANanthropics/skills203k近 7 天新增 3,333 个 star

canary

GAgarrytan/gstack143k近 7 天新增 636 个 star

observability-and-instrumentation

ADaddyosmani/agent-skills122k近 7 天新增 1,627 个 star

精选

shipping-and-launch

上线前逐项检查,规划监控、分阶段发布和回滚方案。

ADaddyosmani/agent-skills122k近 7 天新增 1,627 个 star

paperclip-board

PApaperclipai/paperclip119k近 7 天新增 2,120 个 star

ruview-configure

RUruvnet/RuView106k近 7 天新增 693 个 star