v1.31.0
guíaPatrón · 06_Observabilidadenglishversión en español

Observability Guide

5 minlectura
1018palabras
10secciones
2026-09-21última edición
4cambios

Version: 1.0.0 Date: 2026-02-10 Author: la organización Purpose: Complete observability guide for .NET 10 projects


Index

  1. Introduction
  2. OpenTelemetry (.NET 10)
  3. Serilog
  4. Application Insights
  5. Business Metrics
  6. GDPR and Sensitive Data
  7. Observability Checklist
  8. NuGet Packages
  9. References

1. Introduction

1.1 The three pillars of observability

Observability allows understanding the internal state of a system from its external outputs. It rests on three complementary pillars:

PillarDescriptionToolsQuestion it answers
LogsTextual records of discrete events with structured contextSerilog + Application Insights"What happened?"
MetricsAggregatable numeric values representing system state over timeOpenTelemetry Metrics + App Insights"How much is happening?"
TracesTracking of a request across multiple services and componentsOpenTelemetry Traces + App Insights"Where is it happening?"

1.2 Why observability matters

  • Detect problems before users do - Metrics and alerts allow identifying degradations before they become incidents.
  • Understand system behavior - Distributed traces show the real flow of requests, including times and dependencies.
  • Reduce time to resolution (MTTR) - Structured and correlated logs enable diagnosing problems in minutes instead of hours.
  • Make data-driven decisions - Business metrics provide visibility on the real impact of changes.

2. OpenTelemetry (.NET 10)

2.1 What is OpenTelemetry

OpenTelemetry (OTel) is an open, vendor-neutral standard for generating, collecting, and exporting telemetry data. In .NET 10, the integration is native and recommended by Microsoft as the standard way to instrument applications.

Advantages over proprietary solutions:

  • No vendor lock-in: same code, different backends
  • Native support in .NET 10 (System.Diagnostics)
  • Active community and CNCF standard
  • Auto-instrumentation for common libraries

2.2 Configuration in Program.cs

// Program.cs - Complete OpenTelemetry configuration in .NET 10
using OpenTelemetry.Logs;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

var builder = WebApplication.CreateBuilder(args);

// =============================================
// Shared resource (identifies the service)
// =============================================
var resourceBuilder = ResourceBuilder.CreateDefault()
    .AddService(
        serviceName: "MyCompany.MyApp.Api",
        serviceVersion: "1.0.0",
        serviceInstanceId: Environment.MachineName);

// =============================================
// TRACES
// =============================================
builder.Services.AddOpenTelemetry()
    .WithTracing(tracing =>
    {
        tracing
            .SetResourceBuilder(resourceBuilder)
            // Auto-instrumentation
            .AddAspNetCoreInstrumentation(options =>
            {
                options.RecordException = true;
                options.Filter = httpContext =>
                    !httpContext.Request.Path.StartsWithSegments("/health");
            })
            .AddHttpClientInstrumentation(options =>
            {
                options.RecordException = true;
            })
            .AddSqlClientInstrumentation(options =>
            {
                // RGPD: el texto de la sentencia puede llevar valores literales. Solo en desarrollo.
        options.SetDbStatementForText = builder.Environment.IsDevelopment();
                options.RecordException = true;
            })
            .AddEntityFrameworkCoreInstrumentation(options =>
            {
                // RGPD: el texto de la sentencia puede llevar valores literales. Solo en desarrollo.
        options.SetDbStatementForText = builder.Environment.IsDevelopment();
            })
            // Custom sources
            .AddSource("MyCompany.MyApp.*")
            // Exporters
            .AddConsoleExporter()                      // Development
            .AddAzureMonitorTraceExporter(options =>    // Production
            {
                options.ConnectionString = builder.Configuration
                    .GetConnectionString("ApplicationInsights");
            });
    })
    // =============================================
    // METRICS
    // =============================================
    .WithMetrics(metrics =>
    {
        metrics
            .SetResourceBuilder(resourceBuilder)
            .AddAspNetCoreInstrumentation()
            .AddHttpClientInstrumentation()
            .AddRuntimeInstrumentation()
            // Custom metrics
            .AddMeter("MyCompany.MyApp.Business")
            // Exporters
            .AddConsoleExporter()
            .AddAzureMonitorMetricExporter(options =>
            {
                options.ConnectionString = builder.Configuration
                    .GetConnectionString("ApplicationInsights");
            });
    });

2.3 Custom traces with ActivitySource

using System.Diagnostics;

public class ScholarshipService : IScholarshipService
{
    // Define an activity source per service
    private static readonly ActivitySource ActivitySource =
        new("MyCompany.MyApp.ScholarshipService", "1.0.0");

    private readonly IScholarshipRepository _repository;
    private readonly ILogger<ScholarshipService> _logger;

    public ScholarshipService(IScholarshipRepository repository, ILogger<ScholarshipService> logger)
    {
        _repository = repository;
        _logger = logger;
    }

    public async Task<ScholarshipDto> CreateAsync(CreateScholarshipRequest request, CancellationToken ct)
    {
        // Create a custom trace
        using var activity = ActivitySource.StartActivity(
            "ScholarshipService.Create",
            ActivityKind.Internal);

        // Enrich with attributes
        activity?.SetTag("scholarship.name", request.Name);
        activity?.SetTag("scholarship.amount", request.Amount);

        try
        {
            var scholarship = Scholarship.Create(request.Name, request.Amount);

            // Sub-activity for persistence
            using var dbActivity = ActivitySource.StartActivity("ScholarshipService.Create.Persist");
            await _repository.AddAsync(scholarship, ct);

            activity?.SetTag("scholarship.id", scholarship.Id);
            activity?.SetStatus(ActivityStatusCode.Ok);

            return scholarship.ToDto();
        }
        catch (Exception ex)
        {
            activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
            activity?.RecordException(ex);
            throw;
        }
    }
}

2.4 Custom metrics with Meter

using System.Diagnostics.Metrics;

public class ScholarshipMetrics
{
    // One Meter per business module
    private static readonly Meter Meter = new("MyCompany.MyApp.Business", "1.0.0");

    // Counters
    private static readonly Counter<long> ScholarshipsCreated =
        Meter.CreateCounter<long>(
            "myapp.scholarships.creadas",
            unit: "{scholarship}",
            description: "Total number of grants created");

    private static readonly Counter<long> ApplicationsReceived =
        Meter.CreateCounter<long>(
            "myapp.applications.recibidas",
            unit: "{application}",
            description: "Grant applications received");

    // Histograms
    private static readonly Histogram<double> TiempoProcesamiento =
        Meter.CreateHistogram<double>(
            "myapp.scholarships.procesamiento.duracion",
            unit: "ms",
            description: "Grant processing duration");

    // Gauge (point-in-time value)
    private static readonly ObservableGauge<int> ActiveScholarships =
        Meter.CreateObservableGauge(
            "myapp.scholarships.activas",
            () => GetActiveScholarships(),
            unit: "{scholarship}",
            description: "Number of currently active grants");

    // Public methods to record metrics
    public static void RegistrarScholarshipCreated(string tipo)
    {
        ScholarshipsCreated.Add(1, new KeyValuePair<string, object?>("tipo", tipo));
    }

    public static void RegistrarScholarshipApplication(string status)
    {
        ApplicationsReceived.Add(1, new KeyValuePair<string, object?>("status", status));
    }

    public static void RegistrarTiempoProcesamiento(double milliseconds)
    {
        TiempoProcesamiento.Record(milliseconds);
    }

    private static int GetActiveScholarships() => /* query to DB or cache */ 0;
}

2.5 Exporters

ExporterEnvironmentUsage
ConsoleDevelopmentQuick visualization in terminal
Application InsightsProductionMain platform when cloud.telemetry=app-insights
OTLPBothStandard protocol, compatible with Jaeger, Grafana, etc.

3. Serilog

3.1 Why Serilog

Serilog is the standard for structured logging in .NET. Unlike basic ILogger, Serilog captures properties as structured data instead of plain text, enabling advanced searches and filtering.

FeatureSerilogBasic ILogger
Structured loggingNativeLimited
Sinks (destinations)100+Basic
Enrichers (context)RichManual
Advanced filteringYesLimited
Request loggingOwn middlewareManual

3.2 Bootstrap Logger pattern

// Program.cs - Recommended pattern with bootstrap logger
using Serilog;

// Bootstrap logger: captures errors BEFORE the app is configured
Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .CreateBootstrapLogger();

try
{
    Log.Information("Starting application {ApplicationName}", "MyCompany.MyApp");

    var builder = WebApplication.CreateBuilder(args);

    // Full configuration from appsettings.json
    builder.Host.UseSerilog((context, services, configuration) =>
        configuration
            .ReadFrom.Configuration(context.Configuration)
            .ReadFrom.Services(services));

    // ... configure services ...

    var app = builder.Build();

    // Request logging middleware
    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");
        };
        // Don't log health checks
        options.GetLevel = (httpContext, elapsed, ex) =>
            httpContext.Request.Path.StartsWithSegments("/health")
                ? Serilog.Events.LogEventLevel.Verbose
                : Serilog.Events.LogEventLevel.Information;
    });

    // ... pipeline ...

    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "Application terminated unexpectedly");
    throw;
}
finally
{
    await Log.CloseAndFlushAsync();
}

3.3 Configuration in appsettings.json

{
  "Serilog": {
    "Using": [
      "Serilog.Sinks.Console",
      "Serilog.Sinks.File",
      "Serilog.Sinks.ApplicationInsights"
    ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft.AspNetCore": "Warning",
        "Microsoft.EntityFrameworkCore": "Warning",
        "Microsoft.EntityFrameworkCore.Database.Command": "Warning",
        "System.Net.Http.HttpClient": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext}{NewLine}  {Message:lj}{NewLine}{Exception}"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "logs/app-.log",
          "rollingInterval": "Day",
          "retainedFileCountLimit": 30,
          "fileSizeLimitBytes": 52428800,
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] ({SourceContext}) {Message:lj}{NewLine}{Exception}"
        }
      },
      {
        "Name": "ApplicationInsights",
        "Args": {
          "connectionString": "[From Key Vault in production]",
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      }
    ],
    "Enrich": [
      "FromLogContext",
      "WithMachineName",
      "WithEnvironmentName",
      "WithThreadId",
      "WithCorrelationId"
    ],
    "Properties": {
      "Application": "MyCompany.MyApp",
      "Environment": "Development"
    }
  }
}

3.4 Structured logging: best practices

// =============================================
// CORRECT - Structured logging
// =============================================

// Use placeholders with descriptive names (NO interpolation)
_logger.LogInformation("Grant {ScholarshipId} created by {User} with amount {Amount}",
    scholarship.Id, user, scholarship.Amount);

// Context with PushProperty for multiple logs
using (LogContext.PushProperty("ScholarshipId", scholarshipId))
using (LogContext.PushProperty("OperationId", operacionId))
{
    _logger.LogInformation("Starting grant processing");
    // ... operation ...
    _logger.LogInformation("Processing completed in {ElapsedMs}ms", elapsed);
}

// =============================================
// INCORRECT - Avoid
// =============================================

// String interpolation (loses structure)
_logger.LogInformation($"Grant {scholarship.Id} created");  // NO

// Concatenation
_logger.LogInformation("Grant " + scholarship.Id + " created");  // NO

// Without context
_logger.LogError("Error processing");  // NO - lacks context

4. Application Insights

4.1 Connection string (from Key Vault)

// Program.cs
builder.Services.AddApplicationInsightsTelemetry(options =>
{
    // Connection string comes from Key Vault in production
    options.ConnectionString = builder.Configuration
        .GetConnectionString("ApplicationInsights");
});

// appsettings.json (development)
{
  "ConnectionStrings": {
    "ApplicationInsights": "InstrumentationKey=xxx;IngestionEndpoint=https://..."
  }
}

4.2 TelemetryClient for custom events

public class ScholarshipService : IScholarshipService
{
    private readonly TelemetryClient _telemetry;

    public ScholarshipService(TelemetryClient telemetry)
    {
        _telemetry = telemetry;
    }

    public async Task<ScholarshipDto> CreateAsync(CreateScholarshipRequest request, CancellationToken ct)
    {
        var sw = Stopwatch.StartNew();

        var scholarship = Scholarship.Create(request.Name, request.Amount);
        await _repository.AddAsync(scholarship, ct);

        sw.Stop();

        // Custom event
        _telemetry.TrackEvent("ScholarshipCreated", new Dictionary<string, string>
        {
            ["ScholarshipId"] = scholarship.Id.ToString(),
            ["Tipo"] = request.Tipo ?? "general",
            ["CreadoPor"] = _currentUser.UserId ?? "system"
        }, new Dictionary<string, double>
        {
            ["Amount"] = (double)scholarship.Amount,
            ["DurationMs"] = sw.ElapsedMilliseconds
        });

        return scholarship.ToDto();
    }

    public async Task ProcessLoteAsync(IEnumerable<int> becaIds, CancellationToken ct)
    {
        // Custom metric
        _telemetry.TrackMetric("ScholarshipsProcesadasPorLote", becaIds.Count());

        // Operation with dependency
        using var operation = _telemetry.StartOperation<DependencyTelemetry>("ProcessLoteScholarships");
        operation.Telemetry.Type = "InternalBatch";

        try
        {
            foreach (var id in becaIds)
            {
                await ProcessScholarshipAsync(id, ct);
            }

            operation.Telemetry.Success = true;
        }
        catch (Exception ex)
        {
            operation.Telemetry.Success = false;
            _telemetry.TrackException(ex);
            throw;
        }
    }
}

4.3 Distributed tracing and correlation

Application Insights automatically correlates all operations using TraceId and SpanId when using OpenTelemetry. This enables:

  • End-to-end transaction search: Follow an HTTP request from browser to database
  • Application Map: Visualize dependencies between services
  • Live Metrics Stream: Real-time metrics (requests/s, CPU, exceptions)
  • Failure analysis: Group errors by root cause

5. Business Metrics

5.1 Example metrics by domain

MetricTypeExample valueSuggested alert
Requests per secondCounter150 req/s> 500 req/s (capacity)
Grant applications per hourCounter25/hour< 1/hour during open period
Error rate (5xx)Ratio0.1%> 1%
Response time P95Histogram250ms> 1000ms
Active grantsGauge45< 1 (anomaly)
Approval rateRatio72%< 50% (review criteria)

Configuring dashboards in Azure Monitor / Application Insights with the following sections is recommended:

  1. Overview - Requests/s, errors, P50/P95/P99 latency
  2. Dependencies - SQL, external HTTP, Redis (latency and errors)
  3. Business - Domain metrics (applications, approvals, amounts)
  4. Infrastructure - CPU, memory, GC, active threads

6. GDPR and Sensitive Data

6.1 Data that should NEVER be logged

DataReasonAlternative
PasswordsCredentialsNever log under any circumstances
JWT Tokens / API KeysSession credentialsLog only last 4 characters
DNI / NIEPersonal identifying dataMask: ***4567X
Full emailPersonal dataMask: j***@example.com
Card numbersFinancial data (PCI-DSS)Never log under any circumstances
Medical dataGDPR special categoryNever log under any circumstances
IP addressesPersonal data (anonymize)Truncate last octet: 192.168.1.xxx
Bank account numbersFinancial dataMask: ES** **** **** **** **89

6.2 Filtering sensitive data in Serilog

// Destructuring policy to mask data
public class SensitiveDataDestructuringPolicy : IDestructuringPolicy
{
    public bool TryDestructure(
        object value, ILogEventPropertyValueFactory factory,
        out LogEventPropertyValue? result)
    {
        if (value is CreateScholarshipRequest request)
        {
            result = factory.CreatePropertyValue(new
            {
                request.Name,
                request.Amount,
                Email = MaskEmail(request.Email),
                // Exclude sensitive fields
            }, destructureObjects: true);
            return true;
        }

        result = null;
        return false;
    }

    private static string MaskEmail(string? email)
    {
        if (string.IsNullOrEmpty(email)) return "***";
        var parts = email.Split('@');
        if (parts.Length != 2) return "***";
        return $"{parts[0][0]}***@{parts[1]}";
    }
}

// Register in Serilog
Log.Logger = new LoggerConfiguration()
    .Destructure.With<SensitiveDataDestructuringPolicy>()
    // ...
    .CreateLogger();

6.3 Log retention policies

Log typeRetentionStorage
Application logs (info/debug)30 daysApplication Insights
Error logs90 daysApplication Insights
Audit logs (data access)2 yearsSQL Server / Blob Storage
Security logs (auth)2 yearsSQL Server / Blob Storage
Metrics90 daysApplication Insights

7. Observability Checklist

Before going to production

  • OpenTelemetry configured with traces, metrics and logs
  • Serilog configured with Console + File (development) and Application Insights (production)
  • Structured logging throughout the code (no string interpolation in logs)
  • Sensitive data excluded from logs (GDPR)
  • Application Insights connected with connection string from Key Vault
  • Business metrics defined and instrumented
  • TraceId/SpanId correlated between services
  • Log levels configured by namespace (Microsoft=Warning, App=Information)
  • Health checks with metrics (/health, /health/ready, /health/live)
  • Serilog request logging middleware enabled
  • Alerts configured for critical errors and performance degradation
  • Dashboards created with key business and infrastructure metrics
  • Log retention configured according to GDPR policy

8. NuGet Packages

PackageVersionPurpose
OpenTelemetry1.*OpenTelemetry core
OpenTelemetry.Extensions.Hosting1.*.NET Host integration
OpenTelemetry.Instrumentation.AspNetCore1.*ASP.NET Core auto-instrumentation
OpenTelemetry.Instrumentation.Http1.*HttpClient auto-instrumentation
OpenTelemetry.Instrumentation.SqlClient1.*SQL Client auto-instrumentation
OpenTelemetry.Instrumentation.EntityFrameworkCore1.*EF Core auto-instrumentation
OpenTelemetry.Instrumentation.Runtime1.*Runtime metrics (.NET GC, threads)
OpenTelemetry.Exporter.Console1.*Development exporter
Azure.Monitor.OpenTelemetry.Exporter1.*Application Insights exporter
Serilog.AspNetCore10.*Serilog integration with ASP.NET Core
Serilog.Sinks.Console6.*Console sink
Serilog.Sinks.File6.*File sink
Serilog.Sinks.ApplicationInsights4.*Application Insights sink
Serilog.Enrichers.Environment3.*Environment and machine enricher
Serilog.Enrichers.Thread4.*Thread enricher
Serilog.Enrichers.CorrelationId3.*Correlation enricher
Microsoft.ApplicationInsights.AspNetCore2.*Application Insights SDK

9. References

FileContent
.claude/skills/observability-patterns/Observability patterns skill
_patron/01_Estructura_Tecnica/ESTRUCTURA_TECNICA.mdSection 10 - Application Insights
_patron/03_Consideraciones_Comunes/CONSIDERACIONES.mdGDPR and sensitive data

External documentation

ResourceURL
OpenTelemetry .NETopentelemetry.io/docs/languages/dotnet
Serilog Wikigithub.com/serilog/serilog/wiki
Application Insightslearn.microsoft.com/azure/azure-monitor/app/app-insights-overview
OpenTelemetry + Azure Monitorlearn.microsoft.com/azure/azure-monitor/app/opentelemetry-enable

Document generated: 2026-02-10 la organización

Fuente: ovillo/_patron/06_Observabilidad/GUIA_OBSERVABILIDAD_EN.md

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/_patron/06_Observabilidad/GUIA_OBSERVABILIDAD_EN.mdCopyright 2026 Hugo Valer Rojas · Apache-2.0