PlanTempusApp/Core/SeqLogging/SeqBackgroundService.cs

89 lines
3.2 KiB
C#
Raw Normal View History

using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.Extensions.Hosting;
using PlanTempus.Core.Telemetry;
2025-03-10 15:56:22 +01:00
namespace PlanTempus.Core.SeqLogging
{
public class SeqBackgroundService : BackgroundService
{
private readonly IMessageChannel<ITelemetry> _messageChannel;
private readonly TelemetryClient _telemetryClient;
private readonly SeqLogger<SeqBackgroundService> _seqLogger;
public SeqBackgroundService(TelemetryClient telemetryClient,
IMessageChannel<ITelemetry> messageChannel,
SeqLogger<SeqBackgroundService> seqlogger)
{
_telemetryClient = telemetryClient;
_messageChannel = messageChannel;
_seqLogger = seqlogger;
_telemetryClient.TrackTrace("SeqBackgroundService started");
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
while (!stoppingToken.IsCancellationRequested)
await foreach (var telemetry in _messageChannel.Reader.ReadAllAsync(stoppingToken))
{
try
{
switch (telemetry)
{
case ExceptionTelemetry et:
await _seqLogger.LogAsync(et);
break;
case TraceTelemetry et:
await _seqLogger.LogAsync(et);
break;
case DependencyTelemetry et:
await _seqLogger.LogAsync(et);
break;
case RequestTelemetry et:
await _seqLogger.LogAsync(et);
break;
case EventTelemetry et:
await _seqLogger.LogAsync(et);
break;
2025-02-19 17:53:12 +01:00
default:
throw new NotSupportedException(telemetry.GetType().Name);
}
}
catch
{
throw;
//_telemetryClient.TrackException(ex); this is disabled for now, we need to think about the channel structure first
}
}
}
catch (Exception ex)
{
if (ex is not OperationCanceledException)
{
_telemetryClient.TrackException(ex);
throw;
}
}
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
_telemetryClient.TrackTrace("StopAsync called: Service shutdown started");
_messageChannel.Dispose();
await base.StopAsync(cancellationToken);
}
}
}