chengsc
2025-03-05 f502d8fbef172fa55a0c75a0e0f53aec1cbd3144
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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
    {
        /// <summary>
        ///  添加使用Serilog请求日志
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        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;
        }
    }
}