OF-DL/OF DL.Core/Services/LoggingService.cs

59 lines
1.8 KiB
C#

using OF_DL.Enumerations;
using Serilog;
using Serilog.Core;
using Serilog.Events;
namespace OF_DL.Services;
public class LoggingService : ILoggingService
{
private readonly ILogEventSink? _optionalErrorSink;
public LoggingService(ILogEventSink? optionalErrorSink = null)
{
_optionalErrorSink = optionalErrorSink;
LevelSwitch = new LoggingLevelSwitch();
InitializeLogger();
}
/// <summary>
/// Gets the level switch that controls runtime logging verbosity.
/// </summary>
public LoggingLevelSwitch LevelSwitch { get; }
/// <summary>
/// Updates the minimum logging level at runtime.
/// </summary>
/// <param name="newLevel">The new minimum log level.</param>
public void UpdateLoggingLevel(LoggingLevel newLevel)
{
LevelSwitch.MinimumLevel = (LogEventLevel)newLevel;
Log.Debug("Logging level updated to: {LoggingLevel}", newLevel);
}
/// <summary>
/// Returns the current minimum logging level.
/// </summary>
public LoggingLevel GetCurrentLoggingLevel() => (LoggingLevel)LevelSwitch.MinimumLevel;
private void InitializeLogger()
{
// Set the initial level to Error (until we've read from config)
LevelSwitch.MinimumLevel = LogEventLevel.Error;
LoggerConfiguration loggerConfiguration = new LoggerConfiguration()
.MinimumLevel.ControlledBy(LevelSwitch)
.WriteTo.File("logs/OFDL.txt", rollingInterval: RollingInterval.Day);
if (_optionalErrorSink != null)
{
loggerConfiguration = loggerConfiguration.WriteTo.Sink(_optionalErrorSink,
LogEventLevel.Error);
}
Log.Logger = loggerConfiguration.CreateLogger();
Log.Debug("Logging service initialized");
}
}