using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
namespace QYZH.InteractiveMagazine.Infrastructure.Middleware;
///
/// 操作日志中间件
///
public class OperationLogMiddleware : IMiddleware
{
private readonly ILogger _logger;
///
/// 构造函数
///
/// 日志记录器
public OperationLogMiddleware(ILogger logger)
{
_logger = logger;
}
///
/// 执行中间件
///
/// HTTP上下文
/// 下一个中间件委托
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var stopwatch = Stopwatch.StartNew();
var requestMethod = context.Request.Method;
var requestUrl = context.Request.Path.ToString();
try
{
await next(context);
}
finally
{
stopwatch.Stop();
var elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
_logger.LogInformation(
"请求完成 | {Method} {Url} | 状态码: {StatusCode} | 耗时: {ElapsedMilliseconds}ms",
requestMethod,
requestUrl,
context.Response.StatusCode,
elapsedMilliseconds
);
}
}
}