我们正在 Linux 下使用 Monodevelop 开发一个 C# 项目。
我们已经通过 NuGet 将 Log4Net(1.2.11.0)、Postsharp (4.1.24.0) 和 Postsharp for Log4Net 添加到我们的项目中。
以下代码抛出 IndexOutOfRangeException:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using PostSharp;
using PostSharp.Aspects;
[System.Diagnostics.DebuggerStepThrough]
[Loggable]
class Program
{
static void Main (string[] args)
{
String[] myArray= new String[] { "X" };
for (int i = 0; i <= 100; i++) {
Console.WriteLine (myArray[i]);
}
}
}
不幸的是,Postsharp 甚至没有捕捉到异常。
我们甚至尝试用“[LoggableAttribute]”替换“[Loggable]”,因为类的名称就是这样。
这里是:
using System;
using System.Collections.Generic;
using System.Linq;
using PostSharp;
using PostSharp.Aspects;
using System.Collections;
[Serializable]
public class LoggableAttribute : OnExceptionAspect
{
public override void OnException(MethodExecutionArgs event_args)
{
Logging.SetExecutionTime(DateTime.Now);
Logging.SetParameter("parameters", ParametersToString(event_args));
Logging.SetParameter("method_name", event_args.Method.Name);
Logging.SetParameter("class_name", event_args.Instance.GetType().ToString());
Logging.Error("Error Encountered in " + event_args.Method, event_args.Exception);
}
private static String ParametersToString(MethodExecutionArgs event_args)
{
String output = "";
if (event_args.Method.GetParameters() != null)
{
for (int i = 0; i < event_args.Method.GetParameters().Length; i++)
{
output += String.Format("[{0} = {1}]", event_args.Method.GetParameters()[i].Name, event_args.Method.GetParameters()[i]);
}
}
return output;
}
}
即使是 OnException 中的断点也无济于事。它进不去。
最佳答案
PostSharp 与单声道配合使用效果很好,实际上我已经在那里使用了很长一段时间。我现在无法在您的单声道版本上进行测试(3.2.8 已经很旧了),但是在 4.0.4 上这段代码运行没有问题:
[Loggable]
internal class Program {
private static void Main(string[] args) {
String[] myArray = new String[] {"X"};
for (int i = 0; i <= 100; i++) {
Console.WriteLine(myArray[i]);
}
}
}
[Serializable]
public class LoggableAttribute : OnExceptionAspect {
public override void OnException(MethodExecutionArgs args) {
Console.WriteLine("Caught by postsharp: " + args.Exception);
args.FlowBehavior = FlowBehavior.Continue;
}
}
输出“被 postsharp 捕获:...”并且没有抛出异常。至于 log4net,您自己说它与您的问题没有任何关系 - 您的代码不会进入使用 log4net 的 block 。
所以,只需更新到现代单声道版本就可以了。
关于c# - Linux Mono + Postsharp + Log4Net = 没有自动异常捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32650600/