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)
|
{
|
}
|
}
|