如何切面记录日志
提问
如何切面记录日志
回答
使用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}");
    }
}

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号