码迷,mamicode.com
首页 > 其他好文 > 详细

拦截所有经过IOC的方法

时间:2017-01-20 11:04:05      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:tin   parameter   pes   处理   format   需要   required   入参   sum   

/// <summary>
/// 此类作用:拦截所有经过IOC的方法,日志在Debug模式下记录传入参数,以及产生的错误
/// 日志在Release模式下,只有出错的情况下才会记录传入参数和错误信息
/// </summary>
public class ExceptionLogBehavior : IInterceptionBehavior
{
/// <summary>
/// 日志 Created by ZhangQc 2016.08.17
/// </summary>
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);


/// <summary>
/// 获取当前行为需要拦截的对象类型接口。 Created by ZhangQc 2016.08.17
/// </summary>
/// <returns>所有需要拦截的对象类型接口。</returns>
public IEnumerable<Type> GetRequiredInterfaces()
{
return Type.EmptyTypes;
}

/// <summary>
/// 通过实现此方法来拦截调用并执行所需的拦截行为。 Created by ZhangQc 2016.08.17
/// </summary>
/// <param name="input">调用拦截目标时的输入信息。</param>
/// <param name="getNext">通过行为链来获取下一个拦截行为的委托。</param>
/// <returns>从拦截目标获得的返回信息。</returns>
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
//拦截前
IMethodReturn retvalue = getNext()(input, getNext);

#region 参数部分
#if DEBUG
//如果出现异常,会记录参数
for (int i = 0; i < input.Arguments.Count; i++)
{
var parameter = input.Arguments[i];
Log.DebugFormat("第{0}个参数值为:{1}", i + 1, parameter);
}
#endif
#endregion

#region 异常处理部分

if (retvalue.Exception == null)
{
}
else
{
#if !DEBUG
//如果出现异常,会记录参数
for (int i = 0; i < input.Arguments.Count; i++)
{
var parameter = input.Arguments[i];
Log.DebugFormat("第{0}个参数值为:{1}", i + 1, parameter);
}
#endif
Log.ErrorFormat("方法名称:{0},执行出错:{1}", getNext.Method.Name, retvalue.Exception);
//retvalue.Exception设为null表示异常已经被处理过了
retvalue.Exception = null;
}

#endregion

return retvalue;
}

/// <summary>
/// 获取一个<see cref="Boolean"/>值,该值表示当前拦截行为被调用时,是否真的需要执行某些操作。 Created by ZhangQc 2016.08.17
/// </summary>
public bool WillExecute
{
get { return true; }
}
}

拦截所有经过IOC的方法

标签:tin   parameter   pes   处理   format   需要   required   入参   sum   

原文地址:http://www.cnblogs.com/creater/p/6322057.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!