PlanTempusApp/Core/Logging/SeqBackgroundService.cs

81 lines
2.9 KiB
C#

using Core.Telemetry;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.Extensions.Hosting;
namespace Core.Logging
{
public class SeqBackgroundService : BackgroundService
{
private readonly IMessageChannel<ITelemetry> _messageChannel;
private readonly TelemetryClient _telemetryClient;
private readonly SeqLogger _seqLogger;
public SeqBackgroundService(TelemetryClient telemetryClient,
IMessageChannel<ITelemetry> messageChannel,
SeqLogger seqlogger)
{
_telemetryClient = telemetryClient;
_messageChannel = messageChannel;
_seqLogger = seqlogger;
}
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;
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;
}
_telemetryClient.TrackTrace("Service shutdown started");
}
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
_messageChannel.Dispose();
await base.StopAsync(cancellationToken);
}
}
}