Feat Workers Prioridades y Nivel Serilog
This commit is contained in:
		| @@ -1,3 +1,4 @@ | ||||
| //Elecciones.Api/Program.cs | ||||
| using Elecciones.Database; | ||||
| using Microsoft.EntityFrameworkCore; | ||||
| using Serilog; | ||||
| @@ -13,13 +14,24 @@ using Microsoft.AspNetCore.HttpOverrides; | ||||
| // Esta es la estructura estándar y recomendada. | ||||
| var builder = WebApplication.CreateBuilder(args); | ||||
|  | ||||
| // 1. Configurar Serilog. Esta es la forma correcta de integrarlo. | ||||
| builder.Host.UseSerilog((context, services, configuration) => configuration | ||||
|     .ReadFrom.Configuration(context.Configuration) | ||||
|     .ReadFrom.Services(services) | ||||
|     .Enrich.FromLogContext() | ||||
|     .WriteTo.Console() | ||||
|     .WriteTo.File("logs/api-.log", rollingInterval: RollingInterval.Day)); | ||||
| // 1. Registra el servicio del interruptor como un Singleton. | ||||
| //    Esto asegura que toda la aplicación comparta la MISMA instancia del interruptor. | ||||
| builder.Services.AddSingleton<LoggingSwitchService>(); | ||||
|  | ||||
| builder.Host.UseSerilog((context, services, configuration) => | ||||
| { | ||||
|     // 2. Obtenemos la instancia del interruptor que acabamos de registrar. | ||||
|     var loggingSwitch = services.GetRequiredService<LoggingSwitchService>(); | ||||
|  | ||||
|     configuration | ||||
|         .ReadFrom.Configuration(context.Configuration) | ||||
|         .ReadFrom.Services(services) | ||||
|         .Enrich.FromLogContext() | ||||
|         // 3. Establecemos el nivel mínimo de logging controlado por el interruptor. | ||||
|         .MinimumLevel.ControlledBy(loggingSwitch.LevelSwitch) | ||||
|         .WriteTo.Console() | ||||
|         .WriteTo.File("logs/api-.log", rollingInterval: RollingInterval.Day); // o "logs/worker-.log" | ||||
| }); | ||||
|  | ||||
| // 2. Añadir servicios al contenedor. | ||||
| var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); | ||||
| @@ -83,6 +95,34 @@ builder.Services.Configure<ForwardedHeadersOptions>(options => | ||||
| // 3. Construir la aplicación. | ||||
| var app = builder.Build(); | ||||
|  | ||||
| // --- LÓGICA PARA LEER EL NIVEL DE LOGGING AL INICIO --- | ||||
| // Creamos un scope temporal para leer la configuración de la BD | ||||
| using (var scope = app.Services.CreateScope()) // O 'host.Services.CreateScope()' | ||||
| { | ||||
|     var services = scope.ServiceProvider; | ||||
|     try | ||||
|     { | ||||
|         // El resto de la lógica no cambia | ||||
|         var dbContext = services.GetRequiredService<EleccionesDbContext>(); | ||||
|         var loggingSwitchService = services.GetRequiredService<LoggingSwitchService>(); | ||||
|  | ||||
|         var logLevelConfig = await dbContext.Configuraciones | ||||
|             .AsNoTracking() | ||||
|             .FirstOrDefaultAsync(c => c.Clave == "Logging_Level"); | ||||
|  | ||||
|         if (logLevelConfig != null) | ||||
|         { | ||||
|             loggingSwitchService.SetLoggingLevel(logLevelConfig.Valor); | ||||
|             Console.WriteLine($"--> Nivel de logging inicial establecido desde la BD a: {logLevelConfig.Valor}"); | ||||
|         } | ||||
|     } | ||||
|     catch (Exception ex) | ||||
|     { | ||||
|         // Si hay un error (ej. la BD no está disponible al arrancar), se usará el nivel por defecto 'Information'. | ||||
|         Console.WriteLine($"--> No se pudo establecer el nivel de logging desde la BD: {ex.Message}"); | ||||
|     } | ||||
| } | ||||
|  | ||||
| app.UseForwardedHeaders(); | ||||
|  | ||||
| // Seeder para el usuario admin | ||||
| @@ -150,19 +190,29 @@ using (var scope = app.Services.CreateScope()) | ||||
| { | ||||
|     var services = scope.ServiceProvider; | ||||
|     var context = services.GetRequiredService<EleccionesDbContext>(); | ||||
|     if (!context.Configuraciones.Any(c => c.Clave == "MostrarOcupantes")) | ||||
|  | ||||
|     // Lista de configuraciones por defecto a asegurar | ||||
|     var defaultConfiguraciones = new Dictionary<string, string> | ||||
|     { | ||||
|         context.Configuraciones.Add(new Configuracion { Clave = "MostrarOcupantes", Valor = "true" }); | ||||
|         context.SaveChanges(); | ||||
|         Console.WriteLine("--> Seeded default configuration 'MostrarOcupantes'."); | ||||
|     } | ||||
|     if (!context.Configuraciones.Any(c => c.Clave == "TickerResultadosCantidad")) | ||||
|         { "MostrarOcupantes", "true" }, | ||||
|         { "TickerResultadosCantidad", "3" }, | ||||
|         { "ConcejalesResultadosCantidad", "5" }, | ||||
|         { "Worker_Resultados_Activado", "false" }, | ||||
|         { "Worker_Bajas_Activado", "false" }, | ||||
|         { "Worker_Prioridad", "Resultados" }, | ||||
|         { "Logging_Level", "Information" } | ||||
|     }; | ||||
|  | ||||
|     foreach (var config in defaultConfiguraciones) | ||||
|     { | ||||
|         context.Configuraciones.Add(new Configuracion { Clave = "TickerResultadosCantidad", Valor = "3" }); | ||||
|         context.Configuraciones.Add(new Configuracion { Clave = "ConcejalesResultadosCantidad", Valor = "5" }); | ||||
|         context.SaveChanges(); | ||||
|         Console.WriteLine("--> Seeded default configuration 'TickerResultadosCantidad'."); | ||||
|         if (!context.Configuraciones.Any(c => c.Clave == config.Key)) | ||||
|         { | ||||
|             context.Configuraciones.Add(new Configuracion { Clave = config.Key, Valor = config.Value }); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     context.SaveChanges(); | ||||
|     Console.WriteLine("--> Seeded default configurations."); | ||||
| } | ||||
|  | ||||
| // Configurar el pipeline de peticiones HTTP. | ||||
|   | ||||
		Reference in New Issue
	
	Block a user