1.nuget安装postsharp
2.编写attribute标记
[Serializable] [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)] public class CustomerExceptionLogAttribute : OnMethodBoundaryAspect { private ILog logger; public CustomerExceptionLogAttribute() { logger = new TXTLogger(); } public override void OnException(MethodExecutionArgs args) { base.OnException(args); System.Windows.Forms.MessageBox.Show("OnException:" + args.Method.Name); //logger.Log(string.Format("{0}:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), args.Exception.Message)); } public override void OnEntry(MethodExecutionArgs args) { var method = args.Method; var ps=method.GetParameters(); var pv = args.Arguments; string p = ""; int index = 0; ps.ToList().ForEach(ee=> { var val = pv[index]; //参数值 p+=ee.Name +":"+val+ ":" + ee.ParameterType + " "; index++; }); base.OnEntry(args); System.Windows.Forms.MessageBox.Show("OnEntry:"+args.Method.Name+"|"+p); } public override void OnExit(MethodExecutionArgs args) { base.OnExit(args); System.Windows.Forms.MessageBox.Show("OnExit:" + args.Method.Name); } public override void OnSuccess(MethodExecutionArgs args) { base.OnSuccess(args); System.Windows.Forms.MessageBox.Show("OnSuccess:" + args.Method.Name); } }
3.使用
[CustomerExceptionLog] //给方法打上标记 public decimal GetPercent(int a, int b) { return decimal.Parse(a + "") / decimal.Parse(b + ""); } private void button1_Click(object sender, EventArgs e) { GetPercent(1, 2); } private void button2_Click(object sender, EventArgs e) { var percent = GetPercent(1, 0); }
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
参考:http://www.cnblogs.com/xingluzhe/p/4738150.html
问题1:如果想对类的所有方法定义统一的异常日志记录的特性,怎么办呢?
如果把特性Targets定义为All或class,可以捕获该类的所有的方法的异常
问题2:如果想对程序集(dll)中每个方法定义异常日志记录的特性,怎么呢?
把特性的Targets定义为all或Assembly,然后在AssemblyInfo.cs文件中,新增程序集的特性
From:http://www.cnblogs.com/xuejianxiyang/p/7065797.html