CentralizedLogging 1.2.0

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

CentralizedLogging

Build Status NuGet License: MIT

Librería de logging de auditoría centralizado para microservicios .NET 8 con PostgreSQL JSONB.

Características

  • PostgreSQL JSONB - Payloads dinámicos como JSON nativo
  • Background Queue - Logging no bloqueante con Channel y retry (Polly)
  • Correlation IDs - Trazabilidad distribuida via header X-Correlation-ID
  • Middleware HTTP - Auditoría automática de requests
  • Health Checks - Monitoreo de conectividad a BD
  • Multi-tenant - Aislamiento por TenantId
  • Thread-safe - Diseñado para concurrencia

Estructura del Proyecto

CentralizedLogging.sln
├── CentralizedLogging.Core/       ← Librería NuGet (todo en uno)
│   ├── Configuration/
│   ├── DTOs/
│   ├── Entities/
│   ├── Enums/
│   ├── Extensions/
│   ├── HealthChecks/
│   ├── Interfaces/
│   ├── Middleware/
│   ├── Persistence/
│   └── Services/
├── CentralizedLogging.API/        ← Demo API
├── CentralizedLogging.Tests/      ← Tests
├── scripts/                       ← SQL scripts
├── docs/                          ← Documentación
├── docker-compose.yml
└── Dockerfile

Quick Start

1. Instalar

dotnet add package CentralizedLogging

2. Configurar appsettings.json

{
  "CentralizedLogging": {
    "ConnectionString": "Host=localhost;Port=5432;Database=audit_logs;Username=postgres;Password=your_password",
    "Schema": "audit",
    "TableName": "logs",
    "EnableConsoleLogging": true,
    "EnableBackgroundQueue": true,
    "MaxQueueSize": 10000,
    "RetryCount": 3,
    "RetryBaseDelayMs": 200,
    "ApplicationName": "MyService",
    "EnableRequestAudit": true
  }
}

3. Registrar en Program.cs

using CentralizedLogging.Extensions;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCentralizedLogging(builder.Configuration);

var app = builder.Build();
app.UseCentralizedLogging(); // Middleware opcional
app.Run();

4. Usar

using CentralizedLogging.DTOs;
using CentralizedLogging.Interfaces;

public class UserService(IAuditLogger auditLogger)
{
    public async Task CreateUserAsync(CreateUserDto dto)
    {
        // ... lógica ...

        await auditLogger.LogAsync(new AuditLogRequest
        {
            User = "admin",
            Module = "Users",
            Controller = "UserController",
            Method = "CreateUserAsync",
            Action = "CREATE_USER",
            Status = "SUCCESS",
            Details = new { UserId = 10, Email = dto.Email }
        });
    }
}

Configuración

Opción Default Descripción
ConnectionString "" Connection string PostgreSQL
Schema "audit" Schema de BD
TableName "logs" Nombre de tabla
EnableConsoleLogging true Log a consola via ILogger
EnableBackgroundQueue true Queue en background (no bloqueante)
MaxQueueSize 10000 Tamaño máximo de la cola
RetryCount 3 Intentos de retry
RetryBaseDelayMs 200 Delay base para backoff exponencial
ApplicationName "DefaultApp" Nombre de la aplicación
EnableRequestAudit false Middleware de auditoría HTTP

Base de Datos

Opción A: SQL Script

psql -h localhost -U postgres -d audit_logs -f scripts/001_create_audit_schema.sql

Opción B: Docker

docker-compose up -d

Modelo de Datos

Campo Tipo Requerido Descripción
Id UUID Identificador único (auto-generado)
RecordDateTime TIMESTAMPTZ Fecha/hora UTC del evento (auto-generado)
User VARCHAR(256) Usuario que generó el evento
Module VARCHAR(256) Módulo o servicio de origen
Controller VARCHAR(256) Controlador donde se originó el evento
Method VARCHAR(256) Método que disparó el evento
Action VARCHAR(256) Acción realizada (ej: CREATE_USER, LOGIN)
MachineIp VARCHAR(45) Dirección IP del cliente
Status VARCHAR(50) Estado de la operación (SUCCESS, FAILURE)
Details JSONB Payload dinámico en formato JSON
CorrelationId VARCHAR(64) No ID de correlación para trazabilidad distribuida
TenantId VARCHAR(128) No Identificador de tenant (multi-tenant)
DurationMs BIGINT No Duración de la operación en milisegundos
CREATE TABLE IF NOT EXISTS audit.logs (
    "Id"              UUID            PRIMARY KEY DEFAULT gen_random_uuid(),
    "RecordDateTime"  TIMESTAMPTZ     NOT NULL DEFAULT (now() AT TIME ZONE 'utc'),
    "User"            VARCHAR(256)    NOT NULL,
    "Module"          VARCHAR(256)    NOT NULL,
    "Controller"      VARCHAR(256)    NOT NULL,
    "Method"          VARCHAR(256)    NOT NULL,
    "Action"          VARCHAR(256)    NOT NULL,
    "MachineIp"       VARCHAR(45)     NOT NULL,
    "Status"          VARCHAR(50)     NOT NULL,
    "Details"         JSONB           NOT NULL DEFAULT '{}'::jsonb,
    "CorrelationId"   VARCHAR(64),
    "TenantId"        VARCHAR(128),
    "DurationMs"      BIGINT
);

Ejemplos

Batch

await auditLogger.LogBatchAsync(new[]
{
    new AuditLogRequest { User = "admin", Module = "Bulk", Controller = "ImportController", Method = "ImportAsync", Action = "IMPORT", Status = "SUCCESS" },
    new AuditLogRequest { User = "admin", Module = "Bulk", Controller = "ImportController", Method = "ValidateAsync", Action = "VALIDATE", Status = "SUCCESS" }
});

Multi-tenant

await auditLogger.LogAsync(new AuditLogRequest
{
    User = "tenant-admin",
    Module = "Billing",
    Controller = "InvoiceController",
    Method = "CreateInvoice",
    Action = "INVOICE",
    Status = "SUCCESS",
    TenantId = "tenant-acme"
});

Consultas JSONB

SELECT * FROM audit.logs WHERE "Details" @> '{"email": "test@test.com"}'::jsonb;
SELECT * FROM audit.logs WHERE ("Details"->>'amount')::numeric > 1000;

Testing

dotnet test

NuGet Package

dotnet pack CentralizedLogging.Core -c Release -o ./nupkgs

Docker

docker-compose up -d

License

MIT

Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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.2.0 145 7/16/2026
1.0.1 68 7/16/2026
1.0.0 99 7/7/2026

v1.2.0 - Renamed properties to English (User, Module, Controller, Method, Details) and added Controller/Method fields.