using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; using Microsoft.Extensions.Hosting; using PlanTempus.Core.Telemetry; namespace PlanTempus.Core.SeqLogging { public class SeqBackgroundService : BackgroundService { private readonly IMessageChannel _messageChannel; private readonly TelemetryClient _telemetryClient; private readonly SeqLogger _seqLogger; public SeqBackgroundService(TelemetryClient telemetryClient, IMessageChannel messageChannel, SeqLogger 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; 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); } } }