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

88 lines
2.9 KiB
C#
Raw Normal View History

using System.Collections.Generic;
using Sentry;
using Serilog;
2024-04-18 01:44:37 +02:00
using Serilog.Core;
using Serilog.Exceptions;
using Wino.Core.Domain.Interfaces;
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 IApplicationConfiguration _applicationConfiguration;
public WinoLogger(IPreferencesService preferencesService, IApplicationConfiguration applicationConfiguration)
2025-02-16 11:54:23 +01:00
{
_preferencesService = preferencesService;
_applicationConfiguration = applicationConfiguration;
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;
// Initialize Sentry
SentrySdk.Init(options =>
{
options.Dsn = _applicationConfiguration.SentryDNS;
#if DEBUG
options.Debug = false;
#else
options.Debug = true;
#endif
options.AutoSessionTracking = true;
// Set user context
options.SetBeforeSend((sentryEvent, hint) =>
{
sentryEvent.User = new SentryUser
{
Id = _preferencesService.DiagnosticId
};
return sentryEvent;
});
});
2025-02-16 11:54:23 +01:00
Log.Logger = new LoggerConfiguration()
.MinimumLevel.ControlledBy(_levelSwitch)
.WriteTo.File(fullLogFilePath, retainedFileCountLimit: 3, rollOnFileSizeLimit: true, rollingInterval: RollingInterval.Day)
.WriteTo.Sentry(minimumBreadcrumbLevel: Serilog.Events.LogEventLevel.Information,
minimumEventLevel: Serilog.Events.LogEventLevel.Error)
2025-02-16 11:54:23 +01:00
.WriteTo.Debug()
.Enrich.FromLogContext()
.Enrich.WithExceptionDetails()
.CreateLogger();
2024-04-18 01:44:37 +02:00
}
public void TrackEvent(string eventName, Dictionary<string, string> properties = null)
{
SentrySdk.AddBreadcrumb(eventName, data: properties);
SentrySdk.ConfigureScope(scope =>
{
if (properties != null)
{
foreach (var prop in properties)
{
scope.SetTag(prop.Key, prop.Value);
}
}
});
}
2024-04-18 01:44:37 +02:00
}