A:基础实现

This commit is contained in:
jimmy committed 2025-11-13 19:12:55 +08:00
1 parent c8fde9759f
commit c73c6f1380
5 files changed
+355

No files matched your search

@@ -0,0 +1,67 @@
using System.Diagnostics;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Sharp.Log.Middleware;
public sealed class SharpRequestLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<SharpRequestLoggingMiddleware> _logger;
public SharpRequestLoggingMiddleware(RequestDelegate next, ILogger<SharpRequestLoggingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
var sw = ValueStopwatch.StartNew();
var request = context.Request;
using var scope = _logger.BeginScope(new Dictionary<string, object>
{
["TraceId"] = Activity.Current?.TraceId.ToString() ?? string.Empty,
["SpanId"] = Activity.Current?.SpanId.ToString() ?? string.Empty
});
try
{
_logger.LogInformation("HTTP {Method} {Path} started", request.Method, request.Path);
await _next(context);
var elapsed = sw.GetElapsedMilliseconds();
var status = context.Response?.StatusCode;
var level = status >= 500 ? LogLevel.Error : LogLevel.Information;
_logger.Log(level, "HTTP {Method} {Path} responded {StatusCode} in {Elapsed} ms",
request.Method, request.Path, status, elapsed);
}
catch (Exception ex)
{
var elapsed = sw.GetElapsedMilliseconds();
_logger.LogError(ex, "HTTP {Method} {Path} failed in {Elapsed} ms", request.Method, request.Path, elapsed);
throw;
}
}
private readonly struct ValueStopwatch
{
private static readonly double TimestampToMilliseconds = 1000.0 / Stopwatch.Frequency;
private readonly long _start;
private ValueStopwatch(long start) => _start = start;
public static ValueStopwatch StartNew() => new(Stopwatch.GetTimestamp());
public long GetElapsedMilliseconds() => (long)((Stopwatch.GetTimestamp() - _start) * TimestampToMilliseconds);
}
}
public static class SharpRequestLoggingExtensions
{
public static IApplicationBuilder UseSharpRequestLogging(this IApplicationBuilder app)
{
return app.UseMiddleware<SharpRequestLoggingMiddleware>();
}
}