From d21a12d5b3b63922e47514846d67804a72b29da9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=BD=87=E9=98=B3=20=E9=82=B9?= Date: Mon, 30 Oct 2023 09:20:52 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=AF=B7=E6=B1=82=E8=BF=87?= =?UTF-8?q?=E6=BB=A4=E6=97=A5=E5=BF=97=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 24Hour/Filter/RequestLoggingFilter.cs | 39 +++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 24Hour/Filter/RequestLoggingFilter.cs diff --git a/24Hour/Filter/RequestLoggingFilter.cs b/24Hour/Filter/RequestLoggingFilter.cs new file mode 100644 index 0000000..8576d56 --- /dev/null +++ b/24Hour/Filter/RequestLoggingFilter.cs @@ -0,0 +1,39 @@ +using Elight.Utility.Extensions; +using Microsoft.AspNetCore.Mvc.Filters; +using System.Diagnostics; + +namespace _24Hour.Filter +{ + public class RequestLoggingFilter : IActionFilter + { + private readonly ILogger logger;//注入serilog + private Stopwatch _stopwatch;//统计程序耗时 + public RequestLoggingFilter(ILogger logger) + { + this.logger = logger; + _stopwatch = Stopwatch.StartNew(); + } + public void OnActionExecuted(ActionExecutedContext context) + { + _stopwatch.Stop(); + var request = context.HttpContext.Request; + var response = context.HttpContext.Response; + var info = $"End Required metod:[{request.Method}],Path:[{request.Path}],StatusCode:[{response.StatusCode}],Times[{_stopwatch.Elapsed.TotalMilliseconds}],QueryString[{request.QueryString}],Result[{context.Result.ConvertToJsonStr()}]"; + if (info.Length>1024) + { + info = info.Substring(0, 1024); + } + logger.LogInformation(info); + } + public void OnActionExecuting(ActionExecutingContext context) + { + var request = context.HttpContext.Request; + var info = $"Start request method:[{request?.Method}] path:[{request?.Path}]"; + if (info.Length > 1024) + { + info = info.Substring(0, 1024); + } + logger.LogInformation(info); + } + } +}