Wie überschreibt ich das Format oder den Inhalt der Protokollnachrichten von microsoft.aspnetcore.hosting.diagnostics?C#

Ein Treffpunkt für C#-Programmierer
Anonymous
 Wie überschreibt ich das Format oder den Inhalt der Protokollnachrichten von microsoft.aspnetcore.hosting.diagnostics?

Post by Anonymous »

Frage aus dem Titel. < /p>
Ich versuche, Korrelations -IDs für meine eingehenden Anfragen einzurichten. Ich habe eine Middleware erstellt und einen Serilog -Anreicher über EnrichDiagnosticContext eingerichtet (siehe Code unten). Alles funktioniert einwandfrei, bis auf die Informationsnachrichten, die von microsoft.aspnetcore.hosting.diagnostics stammen. Insbesondere diejenigen, die "Anfrage gestartet" und "Anfrage beendet" haben. Da meine Korrelations -ID Middleware jedoch in späterer Zeit in der Anforderungspipeline ausgeführt wird, wird meine benutzerdefinierte Korrelations -ID nicht festgelegt. < /P>
Beachten Sie die folgenden Protokolle. Die [CID: ] wird von meiner Middleware festgelegt. Es ist in den ersten und letzten Zeilen leer (

Code: Select all

[CID:]
). Einige Eigenschaften wurden für die Kürze entfernt. < /P>

Code: Select all

[2025-05-22 22:57:56.507 +02:00][INF][...][CID:][TraceId:3c383f9b6ec8bf6bf74f561d8576a6c3][Span_Id:b44244018fcf8eaf] Request starting HTTP/1.1 GET http://localhost:5124/WeatherForecast
[2025-05-22 22:57:56.527 +02:00][INF][...][CID:b657f8bc-59f1-400b-86a5-f97814b523a4][TraceId:3c383f9b6ec8bf6bf74f561d8576a6c3][Span_Id:b44244018fcf8eaf] Executing endpoint 'BaseSystem.Api.Controllers.WeatherForecastController.Get (BaseSystem.Api)'
[2025-05-22 22:57:56.542 +02:00][INF][...][CID:b657f8bc-59f1-400b-86a5-f97814b523a4][TraceId:3c383f9b6ec8bf6bf74f561d8576a6c3][Span_Id:b44244018fcf8eaf] Route matched with {action = "Get", controller = "WeatherForecast"}. Executing controller action with signature System.Collections.Generic.IEnumerable`1[BaseSystem.Api.WeatherForecast] Get() on controller BaseSystem.Api.Controllers.WeatherForecastController (BaseSystem.Api).
[2025-05-22 22:57:56.546 +02:00][INF][...][CID:b657f8bc-59f1-400b-86a5-f97814b523a4][TraceId:3c383f9b6ec8bf6bf74f561d8576a6c3][Span_Id:b44244018fcf8eaf] Executing action method BaseSystem.Api.Controllers.WeatherForecastController.Get (BaseSystem.Api) - Validation state: Valid
[2025-05-22 22:57:56.547 +02:00][INF][...][CID:b657f8bc-59f1-400b-86a5-f97814b523a4][TraceId:3c383f9b6ec8bf6bf74f561d8576a6c3][Span_Id:b44244018fcf8eaf] Get Forecasts
[2025-05-22 22:57:56.550 +02:00][INF][...][CID:b657f8bc-59f1-400b-86a5-f97814b523a4][TraceId:3c383f9b6ec8bf6bf74f561d8576a6c3][Span_Id:b44244018fcf8eaf] Executed action method BaseSystem.Api.Controllers.WeatherForecastController.Get (BaseSystem.Api), returned result Microsoft.AspNetCore.Mvc.ObjectResult in 1.4376ms.
[2025-05-22 22:57:56.561 +02:00][INF][...][CID:b657f8bc-59f1-400b-86a5-f97814b523a4][TraceId:3c383f9b6ec8bf6bf74f561d8576a6c3][Span_Id:b44244018fcf8eaf] Executing ObjectResult, writing value of type 'z__ReadOnlyList`1[[BaseSystem.Api.WeatherForecast, BaseSystem.Api, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'.
[2025-05-22 22:57:56.598 +02:00][INF][...][CID:b657f8bc-59f1-400b-86a5-f97814b523a4][TraceId:3c383f9b6ec8bf6bf74f561d8576a6c3][Span_Id:b44244018fcf8eaf] Executed action BaseSystem.Api.Controllers.WeatherForecastController.Get (BaseSystem.Api) in 53.6138ms
[2025-05-22 22:57:56.598 +02:00][INF][...][CID:b657f8bc-59f1-400b-86a5-f97814b523a4][TraceId:3c383f9b6ec8bf6bf74f561d8576a6c3][Span_Id:b44244018fcf8eaf] Executed endpoint 'BaseSystem.Api.Controllers.WeatherForecastController.Get (BaseSystem.Api)'
[2025-05-22 22:57:56.600 +02:00][INF][...][CID:b657f8bc-59f1-400b-86a5-f97814b523a4][TraceId:3c383f9b6ec8bf6bf74f561d8576a6c3][Span_Id:b44244018fcf8eaf] HTTP GET /WeatherForecast responded 200 in 73.9809 ms
[2025-05-22 22:57:56.602 +02:00][INF][...][CID:][TraceId:3c383f9b6ec8bf6bf74f561d8576a6c3][Span_Id:b44244018fcf8eaf] Request finished HTTP/1.1 GET http://localhost:5124/WeatherForecast - 200 null application/json; charset=utf-8 96.6721ms
< /code>
Wie kann meine Korrelations -ID auf Nachrichten angezeigt werden.  ID -Helfer 
[*] Serilog -Konfigurationserweiterungen

[b] Code: [/b] 
// Configuration:

public static WebApplication ConfigureStartup(this WebApplication app)
{
app.UseMiddleware();
app.UseSerilogRequestLogging(opts =>
{
opts.EnrichDiagnosticContext = (diagCtx, httpCtx) =>
{
CorrelationIdHelper.EnrichDiagnosticContext(diagCtx, httpCtx);
};
});
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.UseAuthorization();
app.MapControllers();
return app;
}

// Middleware:
public class CorrelationIdMiddleware
{
private readonly RequestDelegate _next;
public CorrelationIdMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task Invoke(HttpContext context)
{
var correlationId = CorrelationIdHelper.EnsureCorrelationId(context);

using (LogContext.PushProperty(
CorrelationIdHelper.CorrelationIdLogContextPushProperty, correlationId))
{
Baggage.SetBaggage(CorrelationIdHelper.HeaderName, correlationId);
await _next(context);
}
}
}

// CorrelationIdHelper
public static class CorrelationIdHelper
{
public const string HeaderName = "x-correlation-id";
public const string CorrelationIdLogContextPushProperty = "CorrelationId";

public static string EnsureCorrelationId(HttpContext httpContext)
{
string correlationId;
if (httpContext.Request.Headers.TryGetValue(HeaderName, out var headerValue)
&& !string.IsNullOrWhiteSpace(headerValue)
&&  !string.IsNullOrEmpty(headerValue))
{
correlationId = headerValue!;
}
else
{
correlationId = Guid.NewGuid().ToString();
httpContext.Request.Headers.Append(HeaderName, correlationId);
}

httpContext.Response.Headers.TryAdd(HeaderName, correlationId);
Baggage.SetBaggage(HeaderName, correlationId);
return correlationId;
}

public static void EnrichWithCorrelationId(HttpContext httpContext, string correlationId)
{
// Add to Serilog LogContext
LogContext.PushProperty(CorrelationIdLogContextPushProperty, correlationId);

// Add to OTEL Baggage for distributed tracing
Baggage.SetBaggage(HeaderName, correlationId);
}

public static void EnrichDiagnosticContext(IDiagnosticContext diagnosticContext, HttpContext httpContext)
{
var correlationId = EnsureCorrelationId(httpContext);

diagnosticContext.Set(CorrelationIdLogContextPushProperty, correlationId);
EnrichWithCorrelationId(httpContext, correlationId);
}
}

// Logging/Serilog Configuration:
public static IServiceCollection ConfigureLogging(
this IServiceCollection services)
{
services.AddSerilog((services, options) =>
{
options
.MinimumLevel.Override("Microsoft.AspNetCore.Mvc", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.AspNetCore.Hosting.Diagnostics", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.AspNetCore.Routing", LogEventLevel.Information);

options
.ReadFrom.Services(services);

options.ConfigureDefaultLoggingOptions();
});
return services;
}

public static ReloadableLogger CreateBootstrapLogger()
{
return new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.ConfigureDefaultLoggingOptions()
.CreateBootstrapLogger();
}

private static LoggerConfiguration ConfigureDefaultLoggingOptions(this LoggerConfiguration options)
{
var sb = new StringBuilder();

sb
.Append("[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}]")
.Append("[{Level:u3}]")
.Append("[MCN:{MachineName}]")
.Append("[ENV:{EnvironmentName}]")
.Append("[IP:{ClientIp}]")
.Append("[CID:{CorrelationId}]")
.Append("[TraceId:{TraceId}]")
.Append("[Span_Id:{SpanId}]")
.Append(" {Message:lj}{NewLine}{Exception}");

var template = sb.ToString();
sb.Clear();

options
.Enrich.FromLogContext()
.Enrich.WithClientIp()
.Enrich.WithMachineName()
.Enrich.With()
.Enrich.WithRequestHeader(headerName: "User-Agent")
.Enrich.WithEnvironmentName()
.Enrich.WithEnvironmentUserName()
.WriteTo
.Async(conf =>
{
conf.Console(
outputTemplate: template,
formatProvider: CultureInfo.InvariantCulture);
});
return options;
}
}

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post