首页 > 其他分享 >如何切面记录日志

如何切面记录日志

时间:2022-11-01 14:58:49浏览次数:45  
标签:Info log 记录 AttributeTargets 切面 msg using 日志 public

提问

如何切面记录日志

回答

使用MethodDecorator.Fody

using System.Reflection;
using my.Attributes;
using my.Log4Net;
using log4net;
using MethodDecorator.Fody.Interfaces;

[module: Log]

namespace Attributes;
/// <summary>
/// 面向切面日志记录特性
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Assembly | AttributeTargets.Module)]
public class LogAttribute : Attribute, IMethodDecorator
{
    private ILog _log;
    private string? _msg;
    public LogAttribute(string? msg = null) { _msg = msg;
        _log = LogManager.GetLogger(Log4NetConfig.RepositoryName, "Info");
    }
    public void Init(object instance, MethodBase method, object[] args)
    {
        if (null == method) throw new ArgumentNullException("method");
        if (null == instance) throw new ArgumentNullException("instance");
        _log.Info($"{_msg} {string.Join(',',args)}");
    }

    public void OnEntry()
    {
        //_log.Info($"开始:{_msg}");
    }

    public void OnExit()
    {
        //_log.Info($"结束:{_msg}");
    }

    public void OnException(Exception exception)
    {
        _log.Info($"{_msg} 触发异常: {exception.GetType()}: {exception}");
    }
}

标签:Info,log,记录,AttributeTargets,切面,msg,using,日志,public
From: https://www.cnblogs.com/wuhailong/p/16847659.html

相关文章