.netcore 操作记录之全局过滤器

.netcore 实现操作日志记录

  • 最近开发中接到一个需求,需要记录用户每次操作的步骤。注意,不是错误日志。
  • 本人用的是.net6.0, 但大致思路是一样的。🚀
  1. 首先建立实体(英语不是很标准,百度查的,各位亲喷哈 各种反弹。)
    // 日志记录类
     public partial class LogOperation
    {
        /// <summary>
        /// Id
        /// </summary>
        public int Id { get; set; }
        /// <summary>
        /// 操作类型,0新增,1修改,2删除。。。。
        /// </summary>
        public int? Operation { get; set; }
        /// <summary>
        /// 记录描述
        /// </summary>
        public string? Desc { get; set; }
        /// <summary>
        /// 创建人
        /// </summary>
        public string? Creator { get; set; }
        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime? CreateTime { get; set; }
        /// <summary>
        /// 浏览器
        /// </summary>
        public string? Browser { get; set; }
        /// <summary>
        /// 用户账号
        /// </summary>
        public string? Account { get; set; }
        /// <summary>
        /// 操作大类(参会)
        /// </summary>
        public string? Category { get; set; }
        /// <summary>
        /// 操作子类(联系人管理)
        /// </summary>
        public string? SubCategory { get; set; }
        /// <summary>
        /// 操作耗时
        /// </summary>
        public decimal? Cost { get; set; }
        /// <summary>
        /// 请求地址
        /// </summary>
        public string? Path { get; set; }
        /// <summary>
        /// 请求ip
        /// </summary>
        public string? Ip { get; set; }
        /// <summary>
        /// 调用后台方法名称
        /// </summary>
        public string? Method { get; set; }
        /// <summary>
        /// 操作参数
        /// </summary>
        public string? Param { get; set; }
        /// <summary>
        /// 请求结果
        /// </summary>
        public string? Result { get; set; }
        /// <summary>
        /// 操作系统
        /// </summary>
        public string? System { get; set; }
    }
    
  2. 有了刚才建立的实体之后就好办了,准备写一个特性加全局过滤器,只要加到方法上,全局拦截一下。只要找到标记的就记录一次。我这里是讲需要记录的内容通过特性传入的,当然你也可以根据你自己的需求去写。
    • 使用异步actionFilter 只需要实现 他的 :OnActionExecutionAsync 方法 (注意这里的异步不是拦截异步是指的是 当前OnActionExecutionAsync方法内执行的内容是异步的)
	/// <summary>
    /// 日志特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Method, Inherited = true)]
    public class OperationLogAttribute : Attribute
    {
        public string Category { get; set; }
        public string SubCategory { get; set; }
        public string Desc { get; set; }
        public OperationTypeEnum Operation { get; set; }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="category">日志大类</param>
        /// <param name="subCategory">日志小类</param>
        /// <param name="desc">日志描述</param>
        /// <param name="operation">日志操作</param>
        public OperationLogAttribute(string category, string subCategory, string desc, OperationTypeEnum operation)
        {
            Category = category;
            SubCategory = subCategory;
            Desc = desc;
            Operation = operation;
        }
    }
    /// <summary>
    /// 日志过滤器
    /// </summary>
    public class OperationLogFilter : IAsyncActionFilter
    {
        private Account Account;
        private readonly IHttpContextService _http;
        private readonly IRepository<LogOperation> _operationRep;
        private readonly IHttpContextAccessor _httpContextAccessor;
        public OperationLogFilter(IRepository<LogOperation> operationRep, IHttpContextService http, IHttpContextAccessor httpContextAccessor)
        {
            _operationRep = operationRep;
            _http = http;
            _httpContextAccessor = httpContextAccessor;
        }
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            //获取动作方法描述器
            var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
            var method = actionDescriptor?.MethodInfo;
            // 检查是否贴有 日志 特性
            if (method != null && !method.IsDefined(typeof(OperationLogAttribute), true))
            {
                // await next();是开始执行目标方法,我目前不需要接口执行结果
                _ = await next();
                #region 如果需要获取执行结果,可以通过以下方式
                //ActionExecutedContext r = await next();
                //var c = r.Result as ObjectResult;
                //var d = JsonConvert.SerializeObject(c.Value); 
                #endregion
            }
            else
            {
                Account = await _http.Get_Current_User();
                var ip = _httpContextAccessor?.HttpContext?.GetIPV4();
                var userAgent = _httpContextAccessor?.HttpContext?.Request.Headers["User-Agent"];
                var (osFamily, uaFamily) = userAgent.GetBrowerAndSystem();
				// 获取接口执行时间
                var sw = new Stopwatch();
                sw.Start();
                _ = await next();
                sw.Stop();

                foreach (var attributes in method.GetCustomAttributes(true))
                {
                    try
                    {
                        OperationLogAttribute? operationLog = attributes as OperationLogAttribute;
                        if (operationLog != null)
                        {
                            await _operationRep.InsertAsync(new LogOperation
                            {
                                Creator = Account.UserName ??= "未知",
                                Account = Account.AccountName ??= "未知",
                                Browser = uaFamily,
                                System = osFamily,
                                Category = operationLog.Category,
                                SubCategory = operationLog.SubCategory,
                                Desc = operationLog.Desc,
                                Operation = Convert.ToInt32(operationLog.Operation),
                                Path = context.HttpContext.Request.Path.Value,
                                Ip = ip,
                                Cost = sw.ElapsedMilliseconds,
                                Method = actionDescriptor?.ActionName,
                                CreateTime = DateTime.Now,
                                Param = context.ActionArguments.Count > 0 ? JsonConvert.SerializeObject(context.ActionArguments) : "",
                            });
                        }
                    }
                    catch (Exception)
                    {
                        _ = await next();
                    }
                }
            }
        }
    }
  1. 过滤器也写完了,那么接下来就是关键的注册了,不注册相当于白写了嘛🤭找到,启动类Program, 添加如下代码
    在这里插入图片描述
  2. 该写的都写了,那么现在就差怎么使用了。还记得刚开始说的是特性吗,那么标记在方法上就行了。
    在这里插入图片描述
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值