CM.Logging.AspNet 1.0.4

dotnet add package CM.Logging.AspNet --version 1.0.4
                    
NuGet\Install-Package CM.Logging.AspNet -Version 1.0.4
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="CM.Logging.AspNet" Version="1.0.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CM.Logging.AspNet" Version="1.0.4" />
                    
Directory.Packages.props
<PackageReference Include="CM.Logging.AspNet" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add CM.Logging.AspNet --version 1.0.4
                    
#r "nuget: CM.Logging.AspNet, 1.0.4"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package CM.Logging.AspNet@1.0.4
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=CM.Logging.AspNet&version=1.0.4
                    
Install as a Cake Addin
#tool nuget:?package=CM.Logging.AspNet&version=1.0.4
                    
Install as a Cake Tool

README — CM.Logger.AspNet

# CM.Logger.AspNet

`CM.Logger.AspNet` es la extensión de `CM.Logger` para aplicaciones **ASP.NET clásico**, incluyendo:

- WebForms
- ASPX
- MVC 5
- aplicaciones en .NET Framework 4.8

Su objetivo es capturar automáticamente el contexto HTTP y enriquecer los logs con información del request, de forma útil para reproducir errores reportados por usuarios.

Qué hace esta extensión

Además del log base, esta extensión puede capturar automáticamente:

  • usuario autenticado
  • sesión
  • URL
  • método HTTP
  • IP
  • UserAgent
  • CorrelationId
  • QueryString
  • FormData
  • Headers sanitizados
  • archivos enviados (solo metadata)
  • snapshot del request al momento del error

Esto es especialmente útil en sistemas WebForms donde se requiere saber qué datos ingresó el usuario cuando ocurrió el error.


Instalación

Package Manager

Install-Package CM.Logger.AspNet
Dependencias

Este paquete depende de:

CM.Logger

Requisitos

.NET Framework 4.8

ASP.NET clásico

web.config

Global.asax.cs

Configuración de base de datos

Usa la misma tabla y 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 web.config

ConnectionString <connectionStrings> <add name="DefaultConnection" connectionString="Server=.;Database=CM_LOGS;Trusted_Connection=True;Encrypt=True;TrustServerCertificate=True;" providerName="System.Data.SqlClient" /> </connectionStrings>

Registro del módulo de captura de request

<system.web> <httpModules> <add name="CMLoggerRequestCaptureModule" type="CM.Logger.AspNet.Modules.RequestCaptureModule, CM.Logger.AspNet" /> </httpModules> </system.web>

<system.webServer> <modules> <add name="CMLoggerRequestCaptureModule" type="CM.Logger.AspNet.Modules.RequestCaptureModule, CM.Logger.AspNet" /> </modules> </system.webServer>

Configuración en Global.asax.cs

using System; using System.Configuration; using CM.Logger.AspNet.Helpers; using CM.Logger.Models;

public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { var conn = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

    AppLoggerAspNetConfigurator.Configure(new LoggingOptions
    {
        ConnectionString = conn,
        ApplicationName = "ClinicaCotizador",
        EnvironmentName = "DEV",
        ServerName = Environment.MachineName,
        VersionApp = "1.0.0",
        DefaultOrigen = "WEB",
        CaptureMachineName = true,
        CaptureEnvironmentUserName = false,
        ThrowExceptions = false
    });
}

protected void Application_Error(object sender, EventArgs e)
{
    try
    {
        Exception ex = Server.GetLastError();
        if (ex == null)
            return;

        CM.Logger.Static.AppLogger.LogException(
            ex,
            "Error no controlado",
            "Global",
            "Application_Error");
    }
    catch
    {
    }
}

}

Uso básico en páginas ASPX o MVC clásico

Ejemplo simple using CM.Logger.Static;

AppLogger.LogInfo("Página cargada", "Reimpresion", "Page_Load"); Ejemplo en un catch using CM.Logger.Static;

catch (Exception ex) { AppLogger.LogException(ex, "Error al guardar cotización", "HojaCotizacion", "btnGuardar_Click"); throw; } Qué se captura automáticamente en un error

Cuando usas:

AppLogger.LogException(ex, "Mensaje", "Modulo", "Metodo");

esta extensión puede enriquecer el log con:

Url

HttpMethod

Usuario

SessionId

CorrelationId

IpAddress

UserAgent

RequestData

DatosExtraJson

Ejemplo de RequestData guardado

Url: https://midominio/Reimpresion.aspx?id=123 HttpMethod: POST Usuario: ROGER SessionId: abc123 CorrelationId: 7d4b9f... IpAddress: 10.0.0.12 UserAgent: Mozilla/5.0 ...

QueryString: id=123

Form: txtPaciente=Juan Perez ddlSexo=M txtEdad=35

Files: FileName=estudio.pdf; ContentType=application/pdf; ContentLength=182344 Ejemplo de DatosExtraJson { "Fecha":"2026-03-19 13:15:00", "Url":"https://midominio/Reimpresion.aspx?id=123", "HttpMethod":"POST", "Usuario":"ROGER", "SessionId":"abc123", "CorrelationId":"7d4b9f9c7f844f61a7c66f0a2d4d2a8f", "IpAddress":"10.0.0.12", "UserAgent":"Mozilla/5.0", "QueryString":{"id":"123"}, "Form":{"txtPaciente":"Juan Perez","ddlSexo":"M","txtEdad":"35"}, "Headers":{"Accept":"text/html"}, "Files":[{"FileName":"estudio.pdf","ContentType":"application/pdf","ContentLength":182344}] }

Qué filtra automáticamente

Para que el log sea útil y no se llene de ruido, se recomienda filtrar campos típicos de WebForms como:

__VIEWSTATE

__EVENTVALIDATION

__VIEWSTATEGENERATOR

__EVENTTARGET

__EVENTARGUMENT

__LASTFOCUS

Y sanitizar campos sensibles como:

password

pwd

pass

token

access_token

refresh_token

authorization

bearer

jwt

clave

contraseña

secret

apiKey

Casos de uso recomendados

detectar qué datos mandó el usuario cuando falló un CRUD

reconstruir formularios que causaron error

reproducir errores intermitentes

correlacionar errores no controlados con requests reales

Recomendaciones

Registrar siempre Application_Error

Usar LogException en catch controlados

No guardar archivos binarios completos

Guardar solo metadata de archivos

Limitar el tamaño de RequestData si el sistema tiene formularios muy grandes

Arquitectura

CM.Logger.AspNet │ ├── Context ├── Helpers ├── Models ├── Modules └── Sanitization

Licencia

MIT

Product Compatible and additional computed target framework versions.
.NET Framework net48 is compatible.  net481 was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETFramework 4.8

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.4 113 3/20/2026
1.0.3 105 3/19/2026
1.0.2 104 3/19/2026
1.0.1 100 3/19/2026
1.0.0 101 3/18/2026

## v1.0.0- Initial Release
## v1.0.1- fix readme and features
## v1.0.2- fadd new features
## v1.0.3- add request y response http
## v1.0.4- add webcontrols capture

### 🔥 Captura automática de Request HTTP



- Implementación de captura automática de contexto HTTP en ASP.NET (.NET Framework)
- Captura de datos reales enviados por el usuario:

 - QueryString
 - Form Data (inputs del usuario)
 - Headers HTTP
 - URL completa
 - Método HTTP
 - IP del cliente
 - UserAgent

---

### 🎯 Enfoque en debugging en producción

- Permite replicar errores con información real del usuario
- Mejora significativa en diagnóstico de fallos
- Reducción de tiempos de soporte técnico

---

### ⚙️ Context Provider

- Implementación de:
 - `AspNetLogContextProvider`
- Integración directa con `AppLogger`
- Enriquecimiento automático de logs

---

### 🧩 Compatibilidad

- ASP.NET WebForms (.aspx)
- ASP.NET MVC (.NET Framework)
- No requiere middleware

---

### 🛡️ Integración con manejo global de errores

- Compatible con:
 - `Global.asax → Application_Error`

---

### ⚠️ Consideraciones

- Se recomienda:
 - No registrar contraseñas en texto plano
 - Sanitizar datos sensibles
 - Controlar tamaño de request

---

### 🚀 Resultado

- Logging orientado a diagnóstico real
- Trazabilidad completa del request
- Ideal para sistemas legacy en producción