using Cleanuparr.Persistence; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Serilog.Core; using Serilog.Events; namespace Cleanuparr.Infrastructure.Logging; /// /// Manages logging configuration and provides dynamic log level control /// public class LoggingConfigManager { private readonly DataContext _dataContext; private readonly ILogger _logger; private static LoggingLevelSwitch LevelSwitch = new(); public LoggingConfigManager(DataContext dataContext, ILogger logger) { _dataContext = dataContext; _logger = logger; // Load settings from configuration LoadConfiguration(); } /// /// Gets the level switch used to dynamically control log levels /// public LoggingLevelSwitch GetLevelSwitch() => LevelSwitch; /// /// Updates the global log level and persists the change to configuration /// /// The new log level public void SetLogLevel(LogEventLevel level) { _logger.LogCritical("Setting global log level to {level}", level); // Change the level in the switch LevelSwitch.MinimumLevel = level; } /// /// Loads logging settings from configuration /// private void LoadConfiguration() { try { var config = _dataContext.GeneralConfigs .AsNoTracking() .First(); LevelSwitch.MinimumLevel = config.LogLevel; } catch (Exception ex) { // Just log and continue with defaults _logger.LogError(ex, "Failed to load logging configuration, using defaults"); } } }