Asp.Net Core WebApi使用方法过滤器记录日志

在 Asp.Net Core WebApi中,使用方法过滤器拦截请求和响应,对请求和响应的内容进行日志记录,详见代码:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WebApi
{
    /// <summary>
    /// 方法过滤器
    /// </summary>
    public class ActionFilter : IActionFilter
    {
        /// <summary>
        /// 监控日志
        /// </summary>
        public static ILogger LoggerMonitor { get; set; }
        /// <summary>
        /// 错误日志
        /// </summary>
        public static ILogger LoggerError { get; set; }

        /// <summary>
        /// 创建请求日志文本
        /// </summary>
        /// <param name="method">请求方法</param>
        /// <param name="controllerName">控制器名称</param>
        /// <param name="actionName">方法名称</param>
        /// <param name="actionArgs">方法参数</param>
        /// <returns></returns>
        private static string CreateRequestLogText(string method, string controllerName, string actionName, IDictionary<string, object> actionArgs)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"收到请求[{method}]/{controllerName}/{actionName},参数:");
            if (actionArgs.Count > 0)
            {
                foreach (var p in actionArgs)
                {
                    sb.AppendLine($"    " + p.Key + "" + Newtonsoft.Json.JsonConvert.SerializeObject(p.Value));
                }
            }
            else
            {
                sb.AppendLine("");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 创建响应日志文本
        /// </summary>
        /// <param name="method">请求方法</param>
        /// <param name="controllerName">控制器名称</param>
        /// <param name="actionName">方法名称</param>
        /// <param name="result">执行结果</param>
        /// <returns></returns>
        private static string CreateResponseLogText(string method, string controllerName, string actionName, object result)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"完成请求[{method}]/{controllerName}/{actionName},结果:");
            if (result != null)
            {
                sb.AppendLine("    " + Newtonsoft.Json.JsonConvert.SerializeObject(result));
            }
            else
            {
                sb.AppendLine("");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 方法执行前
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (LoggerMonitor != null)
            {
                // 记录请求参数日志
                ControllerActionDescriptor desc = context.ActionDescriptor as ControllerActionDescriptor;
                if (desc != null)
                {
                    var logText = CreateRequestLogText(
                        context.HttpContext.Request.Method,
                        desc.ControllerName,
                        desc.ActionName,
                        context.ActionArguments);
                    LoggerMonitor.Debug(logText);
                }
            }
        }

        /// <summary>
        /// 方法执行后
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Exception != null)
            {
                // 记录异常日志
                if (LoggerError != null)
                {
                    LoggerError.Error(context.Exception, context.Exception.Message);
                }
            }

            if (LoggerMonitor != null)
            {
                // 记录请求结果日志
                ControllerActionDescriptor desc = context.ActionDescriptor as ControllerActionDescriptor;
                if (desc != null)
                {
                    ObjectResult rst = context.Result as ObjectResult;
                    Object rstValue = rst != null ? rst.Value : null;
                    var logText = CreateResponseLogText(
                        context.HttpContext.Request.Method,
                        desc.ControllerName,
                        desc.ActionName,
                        rstValue);
                    LoggerMonitor.Debug(logText);
                }
            }
        }
    }
}

然后,在WebApi的Startup类的ConfigureServices中启用方法过滤器,代码为:

            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(ActionFilter));
            });

 

posted @ 2022-04-26 14:46  广阔之海  阅读(981)  评论(0编辑  收藏  举报