3 回答

TA貢獻1772條經驗 獲得超5個贊
我在 Twitter 上向@davidfowl 提出了同樣的問題。他已回復:
不,沒有什么開箱即用的。有一個端到端的應用程序洞察力,但它不是很充實。您可能會考慮跨團隊使用相同的中間件。如果在 3.0 中有一個工作項來解決這個問題https://github.com/aspnet/Hosting/issues/1350
因此,目前看來,定制中間件是唯一的出路。這可能會隨著未來的版本而改變。
更新
我們最終按照@DavidMcEleney 的建議創建了一個自定義中間件。然而,在它之上我們添加了CorrelationId一個AsyncLocal屬性。這有助于我們在CorrelationId需要時訪問代碼中的任何位置。這是代碼獲取/設置CorrelationId:
using System;
using System.Threading;
public static class CorrelationContext
{
private static readonly AsyncLocal<string> CorrelationId = new AsyncLocal<string>();
public static void SetCorrelationId(string correlationId)
{
if (string.IsNullOrWhiteSpace(correlationId))
{
throw new ArgumentException(nameof(correlationId), "Correlation id cannot be null or empty");
}
if (!string.IsNullOrWhiteSpace(CorrelationId.Value))
{
throw new InvalidOperationException("Correlation id is already set");
}
CorrelationId.Value = correlationId;
}
public static string GetCorrelationId()
{
return CorrelationId.Value;
}
}
用于 CorrelationMiddleware.cs
public class CorrelationMiddleware
{
private readonly RequestDelegate _next;
public CorrelationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
context.Request.Headers.TryGetValue("Correlation-Id-Header", out var correlationIds);
var correlationId = correlationIds.FirstOrDefault() ?? Guid.NewGuid().ToString();
CorrelationContext.SetCorrelationId(correlationId);
using (LogContext.PushProperty("Correlation-Id", correlationId))
{
await _next.Invoke(context);
}
}
}
如果我們CorrelationId稍后需要在代碼中的任何地方訪問 in,那么我們只需調用:CorrelationContext.GetCorrelationId();

TA貢獻1824條經驗 獲得超8個贊
我一直在使用 Serilog 登錄 dotnet core 并一直在使用中間件推送 LogContext 屬性-
相關中間件.cs
public class CorrelationMiddleware
{
readonly RequestDelegate _next;
public CorrelationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
context.Request.Headers.TryGetValue(Headers.Correlation, out StringValues correlationId);
using (LogContext.PushProperty("Correlation-Id", correlationId.FirstOrDefault()))
{
await _next.Invoke(context);
}
}
}
在您的 Startup.cs 配置方法中注冊它:
app.UseMiddleware<CorrelationLogger>();
然后,在進行出站 http 調用時 - 您可以通過添加向 HttpRequestMessage 添加標頭
request.Headers.Add(Headers.Correlation, GetHeader("Correlation-Id"));
在搜索日志時,我們可以通過相關 ID 進行搜索并查看所有 API 之間的完整端到端...
- 3 回答
- 0 關注
- 458 瀏覽
添加回答
舉報