Aspect class看起来像这样:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using PostSharp.Aspects;
namespace GlobalExceptionHandler
{
[Serializable]
class MyDebugger : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
Console.WriteLine("METHOD ENTRY: " + args.Method.Name + "(" + args.Arguments.GetArgument(0) + ")");
}
public override void OnException(MethodExecutionArgs args)
{
Console.WriteLine("Exception at: " + args.Method.Name + "()");
args.FlowBehavior = FlowBehavior.Continue;
}
}
}
我正在将 mscorlib 程序集的方面应用于系统命名空间,但不包括我认为导致我的方面堆栈溢出的控制台类,因为它使用 Console.WriteLine 打印日志。
[assembly: GlobalExceptionHandler.MyDebugger(AttributeTargetAssemblies = "mscorlib", AttributeTargetTypes = "System.Console", AttributeExclude = true, AttributePriority = 100000)]
[assembly: GlobalExceptionHandler.MyDebugger(AttributeTargetAssemblies = "mscorlib", AttributeTargetTypes = "System.*")]
而且我仍然收到堆栈溢出异常
方面代码中的表达式,其中使用"+"添加多个字符串,实际上是作为 C# 编译器对方法String.Concat
调用发出的。所以你在OnEntry
中得到这个代码:
Console.WriteLine(String.Concat("METHOD ENTRY: ", args.Method.Name, "(", args.Arguments.GetArgument(0), ")"));
为了避免递归,您可以像System.Console
一样排除System.String
类。但是,在一般情况下,最好向您方面添加一个线程静态标志,以停止递归调用。
[Serializable]
class MyDebugger : OnMethodBoundaryAspect
{
[ThreadStatic]
private static bool isLogging;
public override void OnEntry( MethodExecutionArgs args )
{
if ( isLogging ) return;
isLogging = true;
Console.WriteLine( "METHOD ENTRY: " + args.Method.Name + "(" + args.Arguments.GetArgument( 0 ) + ")" );
isLogging = false;
}
public override void OnException( MethodExecutionArgs args )
{
if ( isLogging ) return;
isLogging = true;
Console.WriteLine( "Exception at: " + args.Method.Name + "()" );
args.FlowBehavior = FlowBehavior.Continue;
isLogging = false;
}
}