CM.Logging.AspNetCore
1.0.1
dotnet add package CM.Logging.AspNetCore --version 1.0.1
NuGet\Install-Package CM.Logging.AspNetCore -Version 1.0.1
<PackageReference Include="CM.Logging.AspNetCore" Version="1.0.1" />
<PackageVersion Include="CM.Logging.AspNetCore" Version="1.0.1" />
<PackageReference Include="CM.Logging.AspNetCore" />
paket add CM.Logging.AspNetCore --version 1.0.1
#r "nuget: CM.Logging.AspNetCore, 1.0.1"
#:package CM.Logging.AspNetCore@1.0.1
#addin nuget:?package=CM.Logging.AspNetCore&version=1.0.1
#tool nuget:?package=CM.Logging.AspNetCore&version=1.0.1
README — CM.Logger.AspNetCore
# CM.Logger.AspNetCore
`CM.Logger.AspNetCore` es la extensión de `CM.Logger` para aplicaciones **ASP.NET Core**, incluyendo:
- MVC
- Web API
- Razor Pages
- Minimal APIs
Su objetivo es integrar el logger base con el ecosistema moderno de ASP.NET Core usando:
- `IHttpContextAccessor`
- inyección de dependencias
- middleware opcional
- captura automática de contexto HTTP
Qué hace esta extensión
Permite enriquecer automáticamente los logs con:
- usuario autenticado
- IP
- URL
- método HTTP
- UserAgent
- CorrelationId
- contexto del request
- integración con DI
Además, puede complementarse con middleware para capturar request/response en escenarios más avanzados.
Instalación
Package Manager
Install-Package CM.Logger.AspNetCore
.NET CLI
dotnet add package CM.Logger.AspNetCore
Dependencias
Este paquete depende de:
CM.Logger
Requisitos
.NET 8.0 recomendado
ASP.NET Core
Configuración de base de datos
Usa la misma tabla y el mismo SP del paquete base CM.Logger.
Tabla sugerida
CREATE TABLE dbo.AppLog
(
IdLog BIGINT IDENTITY(1,1) NOT NULL PRIMARY KEY,
FechaRegistro DATETIME2(0) NOT NULL CONSTRAINT DF_AppLog_FechaRegistro DEFAULT (SYSDATETIME()),
Nivel VARCHAR(20) NOT NULL,
TipoLog VARCHAR(30) NULL,
Aplicacion VARCHAR(150) NOT NULL,
Ambiente VARCHAR(50) NULL,
Servidor VARCHAR(100) NULL,
Maquina VARCHAR(100) NULL,
VersionApp VARCHAR(50) NULL,
Modulo VARCHAR(150) NULL,
Clase VARCHAR(200) NULL,
Metodo VARCHAR(200) NULL,
Origen VARCHAR(50) NULL,
Usuario VARCHAR(100) NULL,
SessionId VARCHAR(100) NULL,
CorrelationId VARCHAR(100) NULL,
Mensaje VARCHAR(1000) NOT NULL,
Detalle VARCHAR(MAX) NULL,
Excepcion VARCHAR(MAX) NULL,
StackTrace VARCHAR(MAX) NULL,
Url VARCHAR(1000) NULL,
HttpMethod VARCHAR(20) NULL,
IpAddress VARCHAR(50) NULL,
UserAgent VARCHAR(1000) NULL,
RequestData VARCHAR(MAX) NULL,
ResponseData VARCHAR(MAX) NULL,
DatosExtraJson VARCHAR(MAX) NULL,
Entidad VARCHAR(100) NULL,
EntidadId VARCHAR(100) NULL,
CodigoError VARCHAR(50) NULL,
EsRevisado BIT NOT NULL CONSTRAINT DF_AppLog_EsRevisado DEFAULT (0),
FechaRevision DATETIME2(0) NULL,
UsuarioRevision VARCHAR(100) NULL
);
GO
SP sugerido
- Usa el mismo dbo.sp_AppLog_Insert del README de CM.Logger.
Configuración en appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=CM_LOGS;Trusted_Connection=True;Encrypt=True;TrustServerCertificate=True;"
}
}
Configuración en Program.cs
using CM.Logger.AspNetCore.Extensions;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddCmLogging(options =>
{
options.ConnectionString = builder.Configuration.GetConnectionString("DefaultConnection");
options.ApplicationName = "BitacorasEnfermeria";
options.EnvironmentName = builder.Environment.EnvironmentName;
options.ServerName = Environment.MachineName;
options.VersionApp = "1.0.0";
options.DefaultOrigen = "WEB";
options.CaptureMachineName = true;
options.CaptureEnvironmentUserName = false;
options.ThrowExceptions = false;
});
var app = builder.Build();
app.MapDefaultControllerRoute();
app.Run();
Uso en Controllers o Services
Usando el logger estático
using CM.Logger.Static;
AppLogger.LogInfo("Proceso iniciado", "Home", "Index");
Usando DI con ILoggerService
using CM.Logger.Abstractions;
using Microsoft.AspNetCore.Mvc;
public class HomeController : Controller
{
private readonly ILoggerService _logger;
public HomeController(ILoggerService logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogInfo("Entró al Index", "Home", "Index");
return View();
}
}
Ejemplo con excepción
using CM.Logger.Abstractions;
public class CotizacionesService
{
private readonly ILoggerService _logger;
public CotizacionesService(ILoggerService logger)
{
_logger = logger;
}
public void Guardar()
{
try
{
throw new InvalidOperationException("Error de prueba");
}
catch (Exception ex)
{
_logger.LogException(ex, "Error al guardar cotización", "CotizacionesService", "Guardar");
throw;
}
}
}
Qué captura automáticamente
Usuario
Url
HttpMethod
IpAddress
UserAgent
CorrelationId
contexto HTTP actual
Middleware opcional para request/response
En escenarios avanzados, puede agregarse middleware para registrar request y response automáticamente.
Ejemplo de uso
using CM.Logger.AspNetCore.Extensions;
var app = builder.Build();
app.UseCmRequestResponseLogging();
app.MapDefaultControllerRoute(); app.Run();
Recomendación: el middleware de request/response debe usarse con cuidado en producción para evitar registrar datos sensibles o bodies demasiado grandes.
Casos de uso recomendados
errores en APIs
errores en formularios MVC
auditoría básica
trazabilidad de requests
integración con dashboards de monitoreo
Recomendaciones
Sanitizar headers sensibles como Authorization
No registrar contraseñas ni tokens completos
Limitar el tamaño del body si se usa middleware
Evitar registrar archivos binarios completos
Correlacionar con CorrelationId
Arquitectura
CM.Logger.AspNetCore │ ├── Context ├── Extensions └── Middleware
Licencia
MIT
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. 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. |
-
net8.0
- CM.Logger (>= 1.0.2)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
## v1.0.0 - Initial Release
### 🔥 Middleware de logging automático
- Implementación de middleware para captura automática de tráfico HTTP en ASP.NET Core
---
### 🔍 Captura completa de Request
Incluye:
- URL
- Método HTTP
- Headers
- QueryString
- Body (JSON / form)
- IP del cliente
- UserAgent
---
### 📤 Captura de Response
- Status Code
- Response Body
- Tiempo de ejecución
---
### 🎯 Observabilidad avanzada
- Monitoreo de comportamiento real del sistema
- Diagnóstico de errores en producción
- Trazabilidad completa request/response
---
### ⚙️ Integración sencilla
- Uso mediante:
```csharp
app.UseCMLogger();