1 /// <summary>
2 /// 记录日志
3 /// </summary>
4 public class LogAttribute: ActionFilterAttribute
5 {
6 private string LogFlag { get; set; }
7
8 private string ActionArguments { get; set; }
9
10
11 private string RequestBody { get; set; }
12
13 private Stopwatch Stopwatch { get; set; }
14
15 public LogAttribute(string logFlag)
16 {
17 LogFlag = logFlag;
18 }
19
20 public override void OnActionExecuting(ActionExecutingContext context)
21 {
22 base.OnActionExecuting(context);
23
24 // 后续添加了获取请求的请求体,如果在实际项目中不需要删除即可
25 long contentLen = context.HttpContext.Request.ContentLength == null ? 0 : context.HttpContext.Request.ContentLength.Value;
26 if (contentLen > 0)
27 {
28 // 读取请求体中所有内容
29 System.IO.Stream stream = context.HttpContext.Request.Body;
30 if (context.HttpContext.Request.Method == "POST")
31 {
32 stream.Position = 0;
33 }
34 byte[] buffer = new byte[contentLen];
35 stream.Read(buffer, 0, buffer.Length);
36 // 转化为字符串
37 RequestBody = System.Text.Encoding.UTF8.GetString(buffer);
38 }
39
40 ActionArguments = Newtonsoft.Json.JsonConvert.SerializeObject(context.ActionArguments);
41
42 Stopwatch = new Stopwatch();
43 Stopwatch.Start();
44 }
45
46 public override void OnActionExecuted(ActionExecutedContext context)
47 {
48 base.OnActionExecuted(context);
49 Stopwatch.Stop();
50
51 string url = context.HttpContext.Request.Host + context.HttpContext.Request.Path + context.HttpContext.Request.QueryString;
52 string method = context.HttpContext.Request.Method;
53
54 string qs = ActionArguments;
55
56 dynamic result = context.Result.GetType().Name == "EmptyResult" ? new { Value = "无返回结果" } : context.Result as dynamic;
57
58 string res = "在返回结果前发生了异常";
59 try
60 {
61 if (result != null)
62 {
63 res = Newtonsoft.Json.JsonConvert.SerializeObject(result.Value);
64 }
65 }
66 catch (System.Exception)
67 {
68 res = "日志未获取到结果,返回的数据无法序列化";
69 }
70
71
72 Log.Information($"\n 方法:{LogFlag} \n " +
73 $"地址:{url} \n " +
74 $"方式:{method} \n " +
75 $"请求体:{RequestBody} \n " +
76 $"参数:{qs}\n " +
77 $"结果:{res}\n " +
78 $"耗时:{Stopwatch.Elapsed.TotalMilliseconds} 毫秒(指控制器内对应方法执行完毕的时间)");
79
80 }
81
82 }
83
84 //引用
85 [HttpGet, Core.Log("测试get")]
86
87 public ResponseResult<PageRespResult> List([FromQuery] QueryStorageCabinetListReq request)
88 {
89 return _app.GetList(request);
90 }