z8018
2026-02-11 b8fb68b44c29e4667f6ea5746119413809a60a9e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System.Reflection;
using Castle.DynamicProxy;
using KH.WMS.Core.Attributes;
using KH.WMS.Core.Logging;
using Microsoft.Extensions.Logging;
 
namespace KH.WMS.Core.AOP;
 
/// <summary>
/// 拦截器基类
/// </summary>
public class LoggingInterceptor : IInterceptor
{
    private readonly ILoggerService _logger;
 
 
    public LoggingInterceptor(ILoggerService logger)
    {
        _logger = logger;
    }
 
    public void Intercept(IInvocation invocation)
    {
        string methodName = $"{invocation.TargetType.Name}.{invocation.Method.Name}";
        MethodInfo method = invocation.Method;
 
        try
        {
            // 从方法上获取特性
            LogInterceptorAttribute? _attribute = invocation.MethodInvocationTarget.GetCustomAttributes(typeof(LogInterceptorAttribute), false)
                               .FirstOrDefault() as LogInterceptorAttribute;
 
            // 如果方法上没有特性,尝试从类上获取
            if (_attribute == null)
            {
                _attribute = invocation.TargetType.GetCustomAttributes(typeof(LogInterceptorAttribute), false)
                                   .FirstOrDefault() as LogInterceptorAttribute;
            }
            if (_attribute == null)
                return;
 
            // 如果没有特性,使用默认值
            var logLevel = _attribute?.LogLevel ?? LogLevel.Information;
 
            _logger.LogInfo("[方法开始]  -> {MethodName}",
               methodName);
            // 执行方法
            invocation.Proceed();
 
            if (_attribute == null)
                return;
 
            var message = $"[方法结束] <- {methodName}";
 
            _logger.LogInfo(message);
        }
        catch (Exception ex)
        {
            // 异常处理
            OnException(invocation, methodName, ex);
        }
        finally
        {
            // 清理逻辑
            OnFinally(invocation, methodName);
        }
 
    }
 
    /// <summary>
    /// 异常处理
    /// </summary>
    protected void OnException(IInvocation invocation, string methodName, Exception ex)
    {
    }
 
    /// <summary>
    /// 清理逻辑
    /// </summary>
    protected void OnFinally(IInvocation invocation, string methodName)
    {
    }
}