using Microsoft.AspNetCore.Builder; using System; using Serilog; using Serilog.Events; using System.IO; using System.Net; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Headers; using System.Runtime.CompilerServices; using Utility.Tools; using System.Security.Claims; using System.IdentityModel.Tokens.Jwt; using System.Linq; namespace Utility { public static class ApplicationBuilderExtensions { /// /// 添加使用Serilog请求日志 /// /// /// public static IApplicationBuilder UseSerilogRequestLogging(this IApplicationBuilder app) { //允许body重用 app.Use(next => context => { context.Request.EnableBuffering(); return next(context); }); // 添加使用Serilog记录请求日志 app.UseSerilogRequestLogging(options => { // 请求日志输出模板 options.MessageTemplate = "\n {RequestMethod}={_RequestPath} | 状态={StatusCode} | 时间={Elapsed}ms | 操作人={_UserName} \n 请求内容={_RequestBody} \n 返回结果={_ResponseBody}"; // 发出调试级别事件而不是默认事件,将请求日志记录到:Debug日志 options.GetLevel = (httpContext, elapsed, ex) => { var method = httpContext.Request.Method.ToLower(); if (method == "options") return LogEventLevel.Debug; return LogEventLevel.Information; }; // 将其他属性附加到请求完成事件,将请求属性附加可以在模板中使用 options.EnrichDiagnosticContext = (diagnosticContext, httpContext) => { diagnosticContext.Set("_RequestPath", WebUtility.UrlDecode(httpContext.Request.Path + httpContext.Request.QueryString)); var token = httpContext.Request.Headers["Token"].ToString(); if (!string.IsNullOrEmpty(token)) { var handler = new JwtSecurityTokenHandler(); try { var jwtToken = handler.ReadJwtToken(token); var claim = jwtToken.Payload.Claims.FirstOrDefault(s => s.Type == "LoginName"); //foreach (var claim in jwtToken.Payload.Claims) //{ // Console.WriteLine($"{claim.Type}: {claim.Value}"); //} if (claim != null) diagnosticContext.Set("_UserName", claim.Value); else diagnosticContext.Set("_UserName", ""); } catch (Exception) { } } else { diagnosticContext.Set("_UserName", ""); } //请求body var requestContent = "{}"; var method = httpContext.Request.Method.ToLower(); if (method == "post" || method == "put") { httpContext.Request.Body.Position = 0; var requestReader = new StreamReader(httpContext.Request.Body); if (requestReader.BaseStream.Length != 0) requestContent = requestReader.ReadToEnd(); } try { if (httpContext.Request.RouteValues["controller"] != null) { if (httpContext.Request.RouteValues["controller"].ToString().ToLower() == "upapi" || httpContext.Request.RouteValues["controller"].ToString().ToLower() == "downapi") { diagnosticContext.Set("ExternalSystems", true); } else { diagnosticContext.Set("ExternalSystems", false); } } diagnosticContext.Set("_RequestBody", requestContent); diagnosticContext.Set("_Service", AppDomain.CurrentDomain.FriendlyName); } catch (Exception) { } }; }); return app; } } }