logging-observability
БесплатноБез исполняемых скриптовНе проверенProduction-grade logging and observability patterns for ASP.NET Core Razor Pages. Covers structured logging with Serilog, correlation IDs, health checks…
от wshaddix★ 94 звезды на GitHubОб этом скилле
You are a senior .NET architect specializing in observability. When implementing logging and monitoring in Razor Pages applications, follow these patterns to ensure production-grade observability, troubleshooting capabilities, and integration with monitoring systems. Target .NET 8+ with nullable reference types enabled.
Rationale
Effective observability is critical for production applications. Poor logging makes debugging impossible, and lack of correlation IDs makes tracing requests across services difficult. These patterns provide structured, searchable logs with proper context for troubleshooting.
Core Principles
- Structured Logging: Use structured formats (JSON) for machine parsing
- Correlation IDs: Every request gets a unique ID for end-to-end tracing
- Contextual Enrichment: Logs include relevant context (user, endpoint, duration)
- Log Levels: Use appropriate levels (Debug, Info, Warning, Error, Fatal)
- External Sinks: Send logs to centralized systems (Seq, Datadog, CloudWatch)
Pattern 1: Serilog Configuration
NuGet Packages
<PackageReference Include="Serilog.AspNetCore" Version="8.0.*" />
<PackageReference Include="Serilog.Expressions" Version="4.0.*" />
<PackageReference Include="Serilog.Sinks.Seq" Version="7.0.*" /> <!-- Optional -->
Bootstrap Logger (Program.cs Start)
using Serilog;
using Serilog.Debugging;
// Enable Serilog self-logging for diagnostics
SelfLog.Enable(msg => Console.Error.WriteLine($"[SERILOG] {msg}"));
// Create bootstrap logger for startup errors
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console(formatProvider: CultureInfo.CurrentCulture)
.CreateBootstrapLogger();
try
{
Log.Information("Starting web application...");
var builder = WebApplication.CreateBuilder(args);
// ... configure services ...
var app = builder.Build();
await app.RunAsync();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
await Log.CloseAndFlushAsync();
}
Service Registration
public static class LoggingServiceRegistration
{
public static IServiceCollection ConfigureSerilog(
this IServiceCollection services,
IConfiguration configuration)
{
services.AddSerilog((services, lc) => lc
.ReadFrom.Configuration(configuration)
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.Enrich.WithEnvironmentName()
.WriteTo.Console(formatter: new ExpressionTemplate(
"[{@t:hh:mm:ss.fff tt} {@l:u3}] {SourceContext} - {CorrelationId} - {@m}\n{@x}",
theme: TemplateTheme.Code))
.WriteTo.Seq(
configuration["Seq:ServerUrl"] ?? "http://localhost:5341",
apiKey: configuration["Seq:ApiKey"],
formatProvider: CultureInfo.CurrentCulture)
);
return services;
}
}
appsettings.json Configuration
{
"Serilog": {
"Using": ["Serilog.Sinks.Console", "Serilog.Sinks.Seq"],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"Microsoft.AspNetCore": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": ["FromLogContext", "WithMachineName", "WithThreadId"],
"Properties": {
"Application": "MyApp"
}
}
}
Pattern 2: Correlation ID Middleware
public class RequestContextLoggingMiddleware
{
private readonly RequestDelegate _next;
private const string CorrelationHeaderName = "X-Correlation-Id";
public RequestContextLoggingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
var correlationId = GetCorrelationId(httpContext);
// Add to response headers
httpContext.Response.OnStarting(() =>
{
httpContext.Response.Headers[CorrelationHeaderName] = correlationId;
return Task.CompletedTask;
});
using (LogContext.PushProperty("CorrelationId", correlationId))
using (LogContext.PushProperty("RequestPath", httpContext.Request.Path))
using (LogContext.PushProperty("RequestMethod", httpContext.Request.Method))
{
await _next.Invoke(httpContext);
}
}
private static string GetCorrelationId(HttpContext httpContext)
{
httpContext.Request.Headers.TryGetValue(
CorrelationHeaderName, out var correlationId);
return correlationId.FirstOrDefault() ?? httpContext.TraceIdentifier;
}
}
// Extension method for easy registration
Установить logging-observability в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл logging-observability?
Production-grade logging and observability patterns for ASP.NET Core Razor Pages. Covers structured logging with Serilog, correlation IDs, health checks, request logging, OpenTelemetry integration, and diagnostic best practices. Use when setting up structured logging in ASP.NET Core applications, implementing distributed tracing with OpenTelemetry, or configuring health checks and observability.
Как установить скилл logging-observability?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл logging-observability запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic