v1.31.0
conocimientoobservability-patternspatterns/

serilog-config.md

Referencia que observability-patterns carga bajo demanda desde su SKILL.md.

observability-patternsskill
patternscarpeta
6395 Btamaño
2026-09-21último cambio del pack

Guia completa para configurar Serilog en proyectos .NET 10 de la organización.


Configuracion Basica en Program.cs

// Program.cs - Configuracion temprana (antes de builder)
using Serilog;

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
        .Build())
    .CreateLogger();

try
{
    Log.Information("Iniciando aplicacion {ApplicationName}", "MyCompany.MyApp");

    var builder = WebApplication.CreateBuilder(args);
    builder.Host.UseSerilog();

    // ... resto de configuracion ...

    var app = builder.Build();

    // Middleware de logging de requests
    app.UseSerilogRequestLogging(options =>
    {
        options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
        {
            diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
            diagnosticContext.Set("UserAgent", httpContext.Request.Headers.UserAgent.ToString());
            diagnosticContext.Set("UserId", httpContext.User?.Identity?.Name ?? "anonymous");
        };
        // No loguear health checks
        options.GetLevel = (httpContext, elapsed, ex) =>
        {
            if (httpContext.Request.Path.StartsWithSegments("/health"))
                return Serilog.Events.LogEventLevel.Verbose;
            if (ex != null)
                return Serilog.Events.LogEventLevel.Error;
            if (elapsed > 5000)
                return Serilog.Events.LogEventLevel.Warning;
            return Serilog.Events.LogEventLevel.Information;
        };
    });

    // ... pipeline HTTP ...

    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "Error fatal al iniciar la aplicacion");
    throw;
}
finally
{
    await Log.CloseAndFlushAsync();
}

Configuracion en appsettings.json

Desarrollo (appsettings.Development.json)

{
  "Serilog": {
    "Using": ["Serilog.Sinks.Console", "Serilog.Sinks.File"],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Information",
        "Microsoft.AspNetCore": "Warning",
        "Microsoft.EntityFrameworkCore": "Information",
        "Microsoft.EntityFrameworkCore.Database.Command": "Information",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
          "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext}{NewLine}  {Message:lj}{NewLine}{Exception}"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "logs/log-.txt",
          "rollingInterval": "Day",
          "retainedFileCountLimit": 7,
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] ({SourceContext}) {Message:lj}{NewLine}{Exception}"
        }
      }
    ],
    "Enrich": ["FromLogContext", "WithMachineName", "WithThreadId"]
  }
}

Produccion (appsettings.json)

{
  "Serilog": {
    "Using": [
      "Serilog.Sinks.Console",
      "Serilog.Sinks.File",
      "Serilog.Sinks.ApplicationInsights"
    ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "Microsoft.AspNetCore": "Warning",
        "Microsoft.EntityFrameworkCore": "Warning",
        "Microsoft.EntityFrameworkCore.Database.Command": "Warning",
        "System": "Warning",
        "MyCompany": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "logs/log-.txt",
          "rollingInterval": "Day",
          "retainedFileCountLimit": 30,
          "fileSizeLimitBytes": 104857600,
          "rollOnFileSizeLimit": true
        }
      },
      {
        "Name": "ApplicationInsights",
        "Args": {
          "connectionString": "",
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      }
    ],
    "Enrich": ["FromLogContext", "WithMachineName", "WithThreadId"]
  }
}

Niveles de Log por Namespace

NamespaceDesarrolloProduccionMotivo
DefaultDebugInformationTodo lo de la aplicacion
MicrosoftInformationWarningFramework, solo errores en prod
Microsoft.AspNetCoreWarningWarningReduce ruido de middleware
Microsoft.EFCore.Database.CommandInformationWarningVer queries en dev, ocultar en prod
SystemWarningWarningSistema, solo errores
MyCompany.*DebugInformationCodigo propio, maximo detalle en dev

Sinks Disponibles

SinkUsoNuGet
ConsoleDesarrollo, depuracionSerilog.Sinks.Console
FileLogs persistentes rotativosSerilog.Sinks.File
Application InsightsProduccion, Azure MonitorSerilog.Sinks.ApplicationInsights
SeqServidor de logs centralizadoSerilog.Sinks.Seq

Enrichers

// Enrichers enriquecen cada evento con informacion contextual
.Enrich.FromLogContext()           // Propiedades del scope
.Enrich.WithMachineName()          // Name del servidor
.Enrich.WithThreadId()             // ID del thread
.Enrich.WithProcessId()            // ID del proceso
.Enrich.WithEnvironmentName()      // Development/Production

NuGets Necesarios

<ItemGroup>
  <PackageReference Include="Serilog.AspNetCore" Version="10.*" />
  <PackageReference Include="Serilog.Sinks.Console" Version="6.*" />
  <PackageReference Include="Serilog.Sinks.File" Version="6.*" />
  <PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="4.*" />
  <PackageReference Include="Serilog.Enrichers.Environment" Version="3.*" />
  <PackageReference Include="Serilog.Enrichers.Thread" Version="4.*" />
  <PackageReference Include="Serilog.Enrichers.Process" Version="3.*" />
</ItemGroup>

Pattern serilog-config

← Volver a la ficha de observability-patterns

Ovillo v1.31.0tag v1.31.0 (2026-10-06) · sin decisiones posteriores69 skills · 19 agents · 22 hooks · 3 reglas · 15 tools · 103 decisionesfuente: ovillo/.claude/skills/observability-patterns/patterns/serilog-config.mdCopyright 2026 Hugo Valer Rojas · Apache-2.0