AT.BackEnd.Observability
1.2.1
dotnet add package AT.BackEnd.Observability --version 1.2.1
NuGet\Install-Package AT.BackEnd.Observability -Version 1.2.1
<PackageReference Include="AT.BackEnd.Observability" Version="1.2.1" />
<PackageVersion Include="AT.BackEnd.Observability" Version="1.2.1" />
<PackageReference Include="AT.BackEnd.Observability" />
paket add AT.BackEnd.Observability --version 1.2.1
#r "nuget: AT.BackEnd.Observability, 1.2.1"
#:package AT.BackEnd.Observability@1.2.1
#addin nuget:?package=AT.BackEnd.Observability&version=1.2.1
#tool nuget:?package=AT.BackEnd.Observability&version=1.2.1
AT.BackEnd.Observability
Paquete NuGet interno y transversal que centraliza logging estructurado, tracing, métricas y health checks para todas las implementaciones detrás de una única superficie de API: AddAtObservability / UseAtObservability.
Instalación
dotnet add package AT.BackEnd.Observability
Configuración (appsettings.json)
{
"Observability": {
"ServiceName": "AF.BackEnd.Api",
"ServiceVersion": "1.0.0",
"OtlpEndpoint": "http://localhost:4317"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Observability:ServiceName es obligatorio — cada bounded context configura el suyo. Ese mismo nombre se usa como ActivitySource/meter canónico (ver más abajo), así que debe ser consistente en todo el servicio.
LogRequestResponseBodies
Registra el cuerpo de peticiones y respuestas, recortado a MaxLoggedBodyBytes (4096 por
defecto) y pasado por el redactor de datos sensibles. Viene apagado, y conviene dejarlo así
salvo mientras se diagnostica algo concreto: el redactor solo enmascara claves JSON que
contengan password, token, secret, apikey, authorization, ssn o creditcard, así
que cualquier otro dato personal del cuerpo queda en el log en claro.
Corregido en 1.2.1 — con esta opción activa, toda respuesta que hiciera
FlushAsyncdevolvía500 Synchronous operations are disallowed. Afectaba a los health checks (/health/livey/health/ready), que es justo lo que una plataforma como App Service usa para decidir si la instancia está sana. Si estás en 1.2.0 o anterior con esta opción entrue, actualiza o ponla enfalse.
Uso en Program.cs
using AT.BackEnd.Observability.DI;
using AT.BackEnd.Observability.HealthChecks;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAtObservability(builder.Configuration);
builder.Services.AddAtHealthChecks()
.AddCheck<DatabaseHealthCheck>("database", tags: [HealthCheckConventions.ReadyTag]);
var app = builder.Build();
app.UseAtObservability();
app.MapAtHealthChecks();
app.Run();
Esto expone:
/health/live— sin dependencias, siempre responde si el proceso está vivo./health/ready— ejecuta únicamente los checks tageados conHealthCheckConventions.ReadyTag.- Un header/log correlacionado por request vía
X-Correlation-Id(CorrelationIdMiddleware), accesible en cualquier punto del código — incluso fuera de un request HTTP — víaICorrelationIdAccessor. - Traces y métricas exportados por OTLP hacia el endpoint configurado, con la instrumentación automática de ASP.NET Core,
HttpClientySqlClientya habilitada.
Instrumentación manual (traces y métricas propias)
Para que las actividades/métricas que el bounded context cree manualmente no se descarten silenciosamente, deben usar el mismo nombre que Observability:ServiceName — así quedan automáticamente enlazadas por AddAtObservability:
using AT.BackEnd.Observability.Tracing;
using AT.BackEnd.Observability.Metrics;
public sealed class OrderService(IMeterFactory meterFactory)
{
private static readonly ActivitySource Source = ActivitySources.GetOrCreate("AF.BackEnd.Api");
private readonly Meter _meter = meterFactory.Create(MeterNames.For("AF.BackEnd.Api"));
public void CreateOrder(int orderId)
{
using var activity = Source.StartActivity("CreateOrder");
activity?.SetTag("order.id", orderId);
// ...
}
}
Correlación fuera de HTTP
ICorrelationIdAccessor está basado en AsyncLocal, no en HttpContext.Items — funciona también en consumers de mensajería (p. ej. AF.BackEnd.Notifications) que no tienen un request HTTP activo.
🎓 Créditos
Nombre del Paquete: AT.BackEnd.Observability Versión: 1.2.1
Autor
- Nombre: Dayser José Granados Pineda
- Correo Electrónico: djpgranados@gmail.com | daysergranados@hotmail.com
Licencia
Este paquete está bajo la licencia MIT License
Copyright (c) 2025 Dayser José Granados Pineda
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE..
Contacto
Si tienes comentarios, problemas o solicitudes, ¡no dudes en ponerte en contacto conmigo!
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- OpenTelemetry.Api (>= 1.17.0)
- OpenTelemetry.Exporter.OpenTelemetryProtocol (>= 1.17.0)
- OpenTelemetry.Extensions.Hosting (>= 1.17.0)
- OpenTelemetry.Instrumentation.AspNetCore (>= 1.17.0)
- OpenTelemetry.Instrumentation.Http (>= 1.17.0)
- OpenTelemetry.Instrumentation.SqlClient (>= 1.17.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Corrige un 500 en cualquier respuesta que use FlushAsync (los health checks entre ellas) cuando LogRequestResponseBodies esta activo: el stream de captura caia en E/S sincrona, que Kestrel prohibe.