Files
Wino-Mail/Wino.Services/WinoLogger.cs

64 lines
2.4 KiB
C#
Raw Normal View History

using System.Collections.Generic;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Serilog;
2024-04-18 01:44:37 +02:00
using Serilog.Core;
using Serilog.Exceptions;
using Wino.Core.Domain.Interfaces;
using Wino.Services.Misc;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
namespace Wino.Services;
public class WinoLogger : IWinoLogger
2025-02-16 11:35:43 +01:00
{
2025-02-16 11:54:23 +01:00
private readonly LoggingLevelSwitch _levelSwitch = new LoggingLevelSwitch();
private readonly IPreferencesService _preferencesService;
private readonly TelemetryConfiguration _telemetryConfiguration;
2024-04-18 01:44:37 +02:00
public TelemetryClient TelemetryClient { get; private set; }
public WinoLogger(IPreferencesService preferencesService, IApplicationConfiguration applicationConfiguration)
2025-02-16 11:54:23 +01:00
{
_preferencesService = preferencesService;
_telemetryConfiguration = new TelemetryConfiguration(applicationConfiguration.ApplicationInsightsInstrumentationKey);
TelemetryClient = new TelemetryClient(_telemetryConfiguration);
2025-02-16 11:54:23 +01:00
RefreshLoggingLevel();
}
2025-02-16 11:54:23 +01:00
public void RefreshLoggingLevel()
{
#if DEBUG
2025-02-16 11:54:23 +01:00
_levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Debug;
#else
2025-02-16 11:54:23 +01:00
_levelSwitch.MinimumLevel = _preferencesService.IsLoggingEnabled ? Serilog.Events.LogEventLevel.Information : Serilog.Events.LogEventLevel.Fatal;
#endif
2025-02-16 11:54:23 +01:00
}
public void SetupLogger(string fullLogFilePath)
{
// Make sure to set the diagnostic id for the telemetry converter.
// This call seems weird, but it is necessary to make sure the diagnostic id is set.
_preferencesService.DiagnosticId = _preferencesService.DiagnosticId;
2025-02-16 11:54:23 +01:00
var insightsTelemetryConverter = new WinoTelemetryConverter(_preferencesService.DiagnosticId);
Log.Logger = new LoggerConfiguration()
.MinimumLevel.ControlledBy(_levelSwitch)
.WriteTo.File(fullLogFilePath, retainedFileCountLimit: 3, rollOnFileSizeLimit: true, rollingInterval: RollingInterval.Day)
.WriteTo.Debug()
.WriteTo.ApplicationInsights(TelemetryClient, insightsTelemetryConverter, restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Error)
2025-02-16 11:54:23 +01:00
.Enrich.FromLogContext()
.Enrich.WithExceptionDetails()
.CreateLogger();
2024-04-18 01:44:37 +02:00
}
public void TrackEvent(string eventName, Dictionary<string, string> properties = null)
{
if (TelemetryClient == null) return;
TelemetryClient.TrackEvent(eventName, properties);
}
2024-04-18 01:44:37 +02:00
}