64 lines
2.1 KiB
C#
64 lines
2.1 KiB
C#
using Castle.DynamicProxy;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Logger
|
|
{
|
|
public class LoggingInterceptor : IInterceptor
|
|
{
|
|
public void Intercept(IInvocation invocation)
|
|
{
|
|
string className = invocation.TargetType.Name;
|
|
string methodName = invocation.Method.Name;
|
|
|
|
LoggerHelper.InfoWithNotify($"调用 {className}.{methodName}() 开始");
|
|
|
|
var sw = Stopwatch.StartNew();
|
|
|
|
try
|
|
{
|
|
// 执行原方法
|
|
invocation.Proceed();
|
|
|
|
// 如果是异步方法
|
|
if (invocation.Method.ReturnType == typeof(Task) ||
|
|
(invocation.Method.ReturnType.IsGenericType &&
|
|
invocation.Method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>)))
|
|
{
|
|
invocation.ReturnValue = InterceptAsync(invocation, sw);
|
|
return;
|
|
}
|
|
|
|
sw.Stop();
|
|
LoggerHelper.SuccessWithNotify($"调用 {className}.{methodName}() 完成,耗时 {sw.ElapsedMilliseconds} ms");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
sw.Stop();
|
|
LoggerHelper.ErrorWithNotify($"调用 {className}.{methodName}() 异常:{ex.Message}", ex.StackTrace);
|
|
throw;
|
|
}
|
|
}
|
|
|
|
private async Task InterceptAsync(IInvocation invocation, Stopwatch sw)
|
|
{
|
|
try
|
|
{
|
|
await (Task)invocation.ReturnValue;
|
|
sw.Stop();
|
|
LoggerHelper.SuccessWithNotify($"调用 {invocation.TargetType.Name}.{invocation.Method.Name}() 完成,耗时 {sw.ElapsedMilliseconds} ms");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
sw.Stop();
|
|
LoggerHelper.ErrorWithNotify($"调用 {invocation.TargetType.Name}.{invocation.Method.Name}() 异常:{ex.Message}", ex.StackTrace);
|
|
throw;
|
|
}
|
|
}
|
|
}
|
|
}
|