CM.Logger 1.0.2

dotnet add package CM.Logger --version 1.0.2
                    
NuGet\Install-Package CM.Logger -Version 1.0.2
                    
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.Logger" Version="1.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CM.Logger" Version="1.0.2" />
                    
Directory.Packages.props
<PackageReference Include="CM.Logger" />
                    
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.Logger --version 1.0.2
                    
#r "nuget: CM.Logger, 1.0.2"
                    
#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.Logger@1.0.2
                    
#: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.Logger&version=1.0.2
                    
Install as a Cake Addin
#tool nuget:?package=CM.Logger&version=1.0.2
                    
Install as a Cake Tool

CM.Logger

CM.Logger es una biblioteca base para registrar logs, excepciones y eventos de aplicación en SQL Server, pensada para ser reutilizable en distintos tipos de proyectos .NET.

Está diseñada para funcionar como núcleo común y puede extenderse mediante paquetes específicos para:

  • ASP.NET clásico (CM.Logger.AspNet)
  • ASP.NET Core (CM.Logger.AspNetCore)

Características

  • Registro centralizado en SQL Server
  • Soporte para:
    • Info
    • Warning
    • Error
    • Debug
    • Fatal
    • Excepciones
  • Integración con Stored Procedure
  • Compatible con .NET Standard 2.0
  • Reutilizable en:
    • aplicaciones ASP.NET clásicas
    • ASP.NET Core
    • apps de consola
    • servicios Windows
  • Posibilidad de enriquecer logs con contexto adicional

Paquetes relacionados

  • CM.Logger → núcleo
  • CM.Logger.AspNet → integración con ASP.NET clásico / WebForms / MVC 5
  • CM.Logger.AspNetCore → integración con ASP.NET Core

Instalación

Package Manager

Install-Package CM.Logger
.NET CLI
dotnet add package CM.Logger
Configuración básica
using System;
using CM.Logger.Models;
using CM.Logger.Static;

AppLogger.Configure(new LoggingOptions
{
    ConnectionString = "Server=.;Database=CM_LOGS;Trusted_Connection=True;Encrypt=True;TrustServerCertificate=True;",
    ApplicationName = "MiAplicacion",
    EnvironmentName = "DEV",
    ServerName = Environment.MachineName,
    VersionApp = "1.0.0",
    DefaultOrigen = "APP",
    CaptureMachineName = true,
    CaptureEnvironmentUserName = true,
    ThrowExceptions = false
});
Ejemplos de uso
Log informativo
AppLogger.LogInfo("Aplicación iniciada", "Program", "Main");
Warning
AppLogger.LogWarning("El folio llegó vacío", "Cotizaciones", "Validar");
Error
AppLogger.LogError("Ocurrió un error al guardar", "Cotizaciones", "Guardar");
Debug
AppLogger.LogDebug("Entró al método de cálculo", "Servicios", "Calcular");
Fatal
AppLogger.LogFatal("Fallo crítico en inicialización", "Global", "Application_Start");
Excepción
try
{
    int x = 0;
    int y = 10 / x;
}
catch (Exception ex)
{
    AppLogger.LogException(ex, "Error matemático", "Pruebas", "Division");
}
Log manual con LogEntry
using CM.Logger.Models;
using CM.Logger.Static;

AppLogger.Log(new LogEntry
{
    Nivel = "ERROR",
    TipoLog = "EXCEPCION",
    Mensaje = "Error al procesar solicitud",
    Detalle = "Se intentó procesar un registro inválido",
    Entidad = "Cotizacion",
    EntidadId = "12345",
    Modulo = "Cotizaciones",
    Metodo = "Procesar"
});
Estructura sugerida en SQL Server
Tabla AppLog
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
Índices sugeridos
CREATE NONCLUSTERED INDEX IX_AppLog_FechaRegistro
ON dbo.AppLog (FechaRegistro DESC);
GO

CREATE NONCLUSTERED INDEX IX_AppLog_Nivel_Fecha
ON dbo.AppLog (Nivel, FechaRegistro DESC);
GO

CREATE NONCLUSTERED INDEX IX_AppLog_Aplicacion_Fecha
ON dbo.AppLog (Aplicacion, FechaRegistro DESC);
GO

CREATE NONCLUSTERED INDEX IX_AppLog_CorrelationId
ON dbo.AppLog (CorrelationId);
GO
Restricción sugerida de nivel
ALTER TABLE dbo.AppLog
ADD CONSTRAINT CK_AppLog_Nivel
CHECK (Nivel IN ('TRACE', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'FATAL'));
GO
Stored Procedure sugerido
CREATE PROCEDURE dbo.sp_AppLog_Insert
    @Nivel             VARCHAR(20),
    @TipoLog           VARCHAR(30) = NULL,

    @Aplicacion        VARCHAR(150),
    @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),
    @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
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN TRY
        INSERT INTO dbo.AppLog
        (
            FechaRegistro,
            Nivel,
            TipoLog,
            Aplicacion,
            Ambiente,
            Servidor,
            Maquina,
            VersionApp,
            Modulo,
            Clase,
            Metodo,
            Origen,
            Usuario,
            SessionId,
            CorrelationId,
            Mensaje,
            Detalle,
            Excepcion,
            StackTrace,
            Url,
            HttpMethod,
            IpAddress,
            UserAgent,
            RequestData,
            ResponseData,
            DatosExtraJson,
            Entidad,
            EntidadId,
            CodigoError
        )
        VALUES
        (
            SYSDATETIME(),
            @Nivel,
            @TipoLog,
            @Aplicacion,
            @Ambiente,
            @Servidor,
            @Maquina,
            @VersionApp,
            @Modulo,
            @Clase,
            @Metodo,
            @Origen,
            @Usuario,
            @SessionId,
            @CorrelationId,
            @Mensaje,
            @Detalle,
            @Excepcion,
            @StackTrace,
            @Url,
            @HttpMethod,
            @IpAddress,
            @UserAgent,
            @RequestData,
            @ResponseData,
            @DatosExtraJson,
            @Entidad,
            @EntidadId,
            @CodigoError
        );

        SELECT CAST(SCOPE_IDENTITY() AS BIGINT) AS IdLog;
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMessage VARCHAR(4000) = ERROR_MESSAGE();
        DECLARE @ErrorSeverity INT = ERROR_SEVERITY();
        DECLARE @ErrorState INT = ERROR_STATE();

        RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState);
    END CATCH
END
GO
Recomendaciones

En ambientes de desarrollo, usar:

Encrypt=True;TrustServerCertificate=True

En producción, usar certificado válido

No registrar contraseñas, tokens o datos sensibles sin sanitizar

Mantener el SP y la tabla como parte del script de instalación del sistema

Arquitectura interna
CM.Logger
│
├── Abstractions
├── Constants
├── Models
├── Infrastructure
│   ├── Sql
│   └── Context
├── Services
└── Static
Casos de uso recomendados

Registro de errores de negocio

Registro de excepciones no controladas

Auditoría básica

Monitoreo centralizado desde visor MVC o dashboard interno

Licencia

MIT
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  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. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on CM.Logger:

Package Downloads
CM.Logging.AspNetCore

Integración de CM.Logger para ASP.NET Core con soporte de contexto HTTP y middleware.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.2 162 3/19/2026
1.0.1 145 3/18/2026
1.0.0 157 3/18/2026

## v1.0.0 - Initial Release

### 🚀 Core Logging Engine

- Implementación de biblioteca base para logging centralizado en SQL Server
- Arquitectura desacoplada:
 - Models
 - Abstractions
 - Infrastructure
 - Services
- Uso de Stored Procedure para inserción de logs

---

### 🧠 Enriquecimiento automático

- Soporte para captura de:
 - Nombre de máquina
 - Usuario del sistema
 - Ambiente (DEV / QA / PROD)
 - Nombre de aplicación
- Configuración centralizada mediante `LoggingOptions`

---

### 🔍 Manejo de logs y excepciones

- Métodos implementados:
 - `LogInfo`
 - `LogWarning`
 - `LogError`
 - `LogDebug`
 - `LogFatal`
 - `LogException`
- Registro completo de excepciones:
 - Message
 - StackTrace
 - Detalle

---

### ⚙️ Configuración flexible

- Clase `LoggingOptions` para:
 - ConnectionString
 - ApplicationName
 - EnvironmentName
 - VersionApp
 - Origen
- Manejo configurable de errores (`ThrowExceptions`)

---

### 🗄️ Integración SQL Server

- Compatible con `Microsoft.Data.SqlClient`
- Ejecución mediante Stored Procedure
- Soporte para conexiones seguras (Encrypt)

---

### 🔗 Compatibilidad

- .NET Framework
- .NET Core
- .NET 5+
- .NET 8

---

### 🔒 Seguridad

- No se registran datos sensibles automáticamente
- Preparado para sanitización externa