More work on SeqBackgroundService, next step is tests for it.

This commit is contained in:
Janus C. H. Knudsen 2025-02-18 16:23:08 +01:00
parent a139b1ad08
commit 67207cf90b
27 changed files with 237 additions and 190 deletions

View file

@ -1,101 +0,0 @@
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.Extensions.Hosting;
using System.Net.Http.Headers;
using System.Text;
namespace Core.Telemetry
{
public class SeqBackgroundService : BackgroundService
{
private readonly IMessageChannel<ITelemetry> _messageChannel;
private readonly TelemetryClient _telemetryClient;
private readonly HttpClient _httpClient;
public SeqBackgroundService(TelemetryClient telemetryClient,
IMessageChannel<ITelemetry> messageChannel,
HttpClient httpClient)
{
_telemetryClient = telemetryClient;
_messageChannel = messageChannel;
_httpClient = httpClient;
_httpClient = new HttpClient()
{
BaseAddress = new Uri("http://localhost:5341"),
Timeout = TimeSpan.FromSeconds(30)
};
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
while (!stoppingToken.IsCancellationRequested)
await foreach (var message in _messageChannel.Reader.ReadAllAsync(stoppingToken))
{
try
{
var eventTelemetry = message as Microsoft.ApplicationInsights.DataContracts.EventTelemetry;
var level = "Information";
var seqEvent = new Dictionary<string, object>
{
{ "@t", DateTime.UtcNow.ToString("o") },
{ "@mt", eventTelemetry.Name },
{ "@l", level } // "Information", "Warning", "Error", etc.
};
foreach (var prop in eventTelemetry.Context.GlobalProperties)
{
seqEvent.Add(prop.Key, prop.Value);
}
var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(seqEvent), Encoding.UTF8, "application/vnd.serilog.clef");
var key = "4XhWFtY4jJ0NBgohBAFF"; ;
//Gt8hS9ClGNfOCAdswDlW
var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"/ingest/clef?apiKey={key}");
requestMessage.Content = content;
var response = await _httpClient.SendAsync(requestMessage, stoppingToken);
response.EnsureSuccessStatusCode();
//if (!response.IsSuccessStatusCode)
//{
// _telemetryClient.TrackTrace($"HTTP kald fejlede med status {response.StatusCode}", Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Warning);
// continue;
//}
}
catch (Exception ex)
{
//_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);
}
}
}

View file

@ -1,238 +0,0 @@
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using System.Text;
using System.Text.Json;
namespace Core.Telemetry
{
public record SeqConfiguration(string IngestionEndpoint, string ApiKey, string Environment);
public class SeqHttpClient
{
HttpClient _httpClient;
public SeqHttpClient(SeqConfiguration seqConfiguration, HttpMessageHandler httpMessageHandler)
{
_httpClient = new HttpClient(httpMessageHandler)
{
BaseAddress = new Uri(seqConfiguration.IngestionEndpoint),
Timeout = TimeSpan.FromSeconds(30)
};
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
if (seqConfiguration.ApiKey != null)
_httpClient.DefaultRequestHeaders.Add("X-Seq-ApiKey", seqConfiguration.ApiKey);
}
public SeqHttpClient(SeqConfiguration seqConfiguration) : this(seqConfiguration, new HttpClientHandler()) { }
public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage httpRequestMessage, CancellationToken cancellationToken)
{
return await _httpClient.SendAsync(httpRequestMessage, cancellationToken);
}
}
public class SeqLogger
{
private readonly SeqHttpClient _httpClient;
private readonly string _environmentName;
private readonly string _machineName;
private readonly SeqConfiguration _configuration;
public SeqLogger(SeqHttpClient httpClient, string environmentName, SeqConfiguration configuration)
{
_httpClient = httpClient;
_environmentName = configuration.Environment;
_machineName = Environment.MachineName;
}
public async Task LogAsync(TraceTelemetry trace, CancellationToken cancellationToken = default)
{
var seqEvent = new Dictionary<string, object>
{
{ "@t", trace.Timestamp.UtcDateTime.ToString("o") },
{ "@mt", trace.Message },
{ "@l", MapSeverityToLevel(trace.SeverityLevel) },
{ "Environment", _environmentName },
{ "MachineName", _machineName }
};
foreach (var prop in trace.Properties)
{
seqEvent.Add(prop.Key, prop.Value);
}
await SendToSeqAsync(seqEvent, cancellationToken);
}
public async Task LogAsync(EventTelemetry evt, CancellationToken cancellationToken = default)
{
var seqEvent = new Dictionary<string, object>
{
{ "@t", evt.Timestamp.UtcDateTime.ToString("o") },
{ "@mt", evt.Name },
{ "@l", "Information" },
{ "Environment", _environmentName },
{ "MachineName", _machineName }
};
foreach (var prop in evt.Properties)
{
seqEvent.Add(prop.Key, prop.Value);
}
foreach (var metric in evt.Metrics)
{
seqEvent.Add($"metric_{metric.Key}", metric.Value);
}
await SendToSeqAsync(seqEvent, cancellationToken);
}
public async Task LogAsync(ExceptionTelemetry ex, CancellationToken cancellationToken = default)
{
var seqEvent = new Dictionary<string, object>
{
{ "@t", ex.Timestamp.UtcDateTime.ToString("o") },
{ "@mt", ex.Exception.Message },
{ "@l", "Error" },
{ "@x", FormatExceptionForSeq(ex.Exception) },
{ "Environment", _environmentName },
{ "MachineName", _machineName },
{ "ExceptionType", ex.Exception.GetType().Name },
};
foreach (var prop in ex.Properties)
{
seqEvent.Add(prop.Key, prop.Value);
}
await SendToSeqAsync(seqEvent, cancellationToken);
}
public async Task LogAsync(DependencyTelemetry dep, CancellationToken cancellationToken = default)
{
var seqEvent = new Dictionary<string, object>
{
{ "@t", dep.Timestamp.UtcDateTime.ToString("o") },
{ "@mt", $"Dependency: {dep.Name}" },
{ "@l", dep.Success??true ? "Information" : "Error" },
{ "Environment", _environmentName },
{ "MachineName", _machineName },
{ "DependencyType", dep.Type },
{ "Target", dep.Target },
{ "Duration", dep.Duration.TotalMilliseconds }
};
foreach (var prop in dep.Properties)
{
seqEvent.Add(prop.Key, prop.Value);
}
await SendToSeqAsync(seqEvent, cancellationToken);
}
public async Task LogAsync(RequestTelemetry req, CancellationToken cancellationToken = default)
{
var seqEvent = new Dictionary<string, object>
{
{ "@t", req.Timestamp.UtcDateTime.ToString("o") },
{ "@mt", $"Request: {req.Name}" },
{ "@l", req.Success??true ? "Information" : "Error" },
{ "Environment", _environmentName },
{ "MachineName", _machineName },
{ "Url", req.Url },
{ "ResponseCode", req.ResponseCode },
{ "Duration", req.Duration.TotalMilliseconds }
};
foreach (var prop in req.Properties)
{
seqEvent.Add(prop.Key, prop.Value);
}
await SendToSeqAsync(seqEvent, cancellationToken);
}
private async Task SendToSeqAsync(Dictionary<string, object> seqEvent, CancellationToken cancellationToken)
{
var content = new StringContent(
Newtonsoft.Json.JsonConvert.SerializeObject(seqEvent),
Encoding.UTF8,
"application/vnd.serilog.clef");
var requestMessage = new HttpRequestMessage(HttpMethod.Post, "/ingest/clef")
{
Content = content
};
var result = await _httpClient.SendAsync(requestMessage, cancellationToken);
result.EnsureSuccessStatusCode();
}
private string MapSeverityToLevel(SeverityLevel? severity)
{
return severity switch
{
SeverityLevel.Verbose => "Verbose",
SeverityLevel.Information => "Information",
SeverityLevel.Warning => "Warning",
SeverityLevel.Error => "Error",
SeverityLevel.Critical => "Fatal",
_ => "Information"
};
}
private string FormatExceptionForSeq(Exception ex)
{
var sb = new StringBuilder();
var exceptionCount = 0;
void FormatSingleException(Exception currentEx, int depth)
{
if (depth > 0) sb.AppendLine("\n--- Inner Exception ---");
sb.AppendLine($"Exception Type: {currentEx.GetType().FullName}");
sb.AppendLine($"Message: {currentEx.Message}");
sb.AppendLine($"Source: {currentEx.Source}");
sb.AppendLine($"HResult: 0x{currentEx.HResult:X8}");
sb.AppendLine("Stack Trace:");
sb.AppendLine(currentEx.StackTrace?.Trim());
if (currentEx.Data.Count > 0)
{
sb.AppendLine("Additional Data:");
foreach (var key in currentEx.Data.Keys)
{
sb.AppendLine($" {key}: {currentEx.Data[key]}");
}
}
}
void RecurseExceptions(Exception currentEx, int depth = 0)
{
if (currentEx is AggregateException aggEx)
{
foreach (var inner in aggEx.InnerExceptions)
{
RecurseExceptions(inner, depth);
depth++;
}
}
else if (currentEx.InnerException != null)
{
RecurseExceptions(currentEx.InnerException, depth + 1);
}
FormatSingleException(currentEx, depth);
exceptionCount++;
}
RecurseExceptions(ex);
sb.Insert(0, $"EXCEPTION CHAIN ({exceptionCount} exceptions):\n");
return sb.ToString();
}
}
}

View file

@ -3,13 +3,13 @@ using System.Net.Http.Headers;
namespace Core.Telemetry
{
public class DebugTelemetryChannel : InMemoryChannel, ITelemetryChannel
public class SeqLoggingTelemetryChannel : InMemoryChannel, ITelemetryChannel
{
private readonly string _filePath;
public ITelemetryChannel _defaultChannel;
static HttpClient _client = new HttpClient();
static DebugTelemetryChannel()
static SeqLoggingTelemetryChannel()
{
_client = new HttpClient()
{
@ -22,7 +22,7 @@ namespace Core.Telemetry
}
public DebugTelemetryChannel(string filePath)
public SeqLoggingTelemetryChannel(string filePath)
{
_filePath = filePath;
}