| | | 1 | | using Microsoft.Extensions.Configuration; |
| | | 2 | | using NpgsqlTypes; |
| | | 3 | | using System; |
| | | 4 | | using Serilog; |
| | | 5 | | using Serilog.Events; |
| | | 6 | | using Serilog.Sinks.PostgreSQL; |
| | | 7 | | |
| | | 8 | | namespace FAU.Entidades.Auditoria |
| | | 9 | | { |
| | | 10 | | public class Auditoria |
| | | 11 | | { |
| | | 12 | | public static void IniciarAuditoria(IConfiguration config) |
| | | 13 | | { |
| | | 14 | | // Build base logger from configuration (levels, enrichers, etc.) |
| | 0 | 15 | | var loggerConfig = new LoggerConfiguration() |
| | 0 | 16 | | .ReadFrom.Configuration(config); |
| | | 17 | | |
| | | 18 | | // Add console sink for local verification (show properties), then read audit DB connection and table name f |
| | 0 | 19 | | loggerConfig = loggerConfig.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} |
| | | 20 | | |
| | | 21 | | // Read audit DB connection and table name from configuration |
| | 0 | 22 | | var auditConn = config.GetConnectionString("DefaultConnection"); |
| | 0 | 23 | | var tableName = "bitacora_auditoria"; |
| | 0 | 24 | | if (!string.IsNullOrWhiteSpace(auditConn)) |
| | | 25 | | { |
| | | 26 | | // configure column writers explicitly to avoid issues with JSON type resolution |
| | 0 | 27 | | var columnWriters = new Dictionary<string, ColumnWriterBase> |
| | 0 | 28 | | { |
| | 0 | 29 | | { "usuario_id", new SinglePropertyColumnWriter("usuario_id", PropertyWriteMethod.Raw, NpgsqlDbType.B |
| | 0 | 30 | | { "accion_id", new SinglePropertyColumnWriter("accion_id", PropertyWriteMethod.Raw, NpgsqlDbType.Big |
| | 0 | 31 | | { "contexto_id", new SinglePropertyColumnWriter("contexto_id", PropertyWriteMethod.Raw, NpgsqlDbType |
| | 0 | 32 | | { "host", new SinglePropertyColumnWriter("host", PropertyWriteMethod.Raw, NpgsqlDbType.Text) }, |
| | 0 | 33 | | { "fecha", new TimestampColumnWriter(NpgsqlDbType.Timestamp) } |
| | 0 | 34 | | }; |
| | | 35 | | |
| | 0 | 36 | | loggerConfig = loggerConfig.WriteTo.PostgreSQL( |
| | 0 | 37 | | auditConn, |
| | 0 | 38 | | tableName, |
| | 0 | 39 | | columnWriters, |
| | 0 | 40 | | formatProvider: null, |
| | 0 | 41 | | restrictedToMinimumLevel: LogEventLevel.Information, |
| | 0 | 42 | | batchSizeLimit: 1000, |
| | 0 | 43 | | period: TimeSpan.FromSeconds(2), |
| | 0 | 44 | | useCopy: false); |
| | | 45 | | } |
| | | 46 | | |
| | | 47 | | |
| | 0 | 48 | | Serilog.Debugging.SelfLog.Enable(msg => Console.Error.WriteLine("Serilog SelfLog: " + msg)); |
| | 0 | 49 | | Log.Logger = loggerConfig.CreateLogger(); |
| | 0 | 50 | | } |
| | | 51 | | } |
| | | 52 | | } |