using Microsoft.ApplicationInsights; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Channels; using System.Threading.Tasks; namespace Core.Telemetry { public class SeqBackgroundService : BackgroundService { private readonly Channel _channel; private readonly HttpClient _client; private readonly string _url; private readonly TelemetryClient _telemetryClient; public SeqBackgroundService(TelemetryClient telemetryClient, Configurations.IConfiguration configuration) { _telemetryClient = telemetryClient; _url = configuration["Seq:Url"]; // eller hvor din Seq URL kommer fra _client = new HttpClient(); _channel = Channel.CreateUnbounded(); } public void EnqueueMessage(string message) { _channel.Writer.TryWrite(message); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { await foreach (var message in _channel.Reader.ReadAllAsync(stoppingToken)) { await _client.PostAsync(_url, new StringContent(message), stoppingToken); } } catch (Exception ex) { _telemetryClient.TrackException(ex); } } } public override async Task StopAsync(CancellationToken cancellationToken) { _channel.Writer.Complete(); await base.StopAsync(cancellationToken); } } }