标签:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
namespace VirtualRemote.log4net
{
public class LogHandler : ICallHandler
{
/// <summary>
/// ICallHandler的成员,表执行顺序
/// </summary>
public int Order
{
get;
set;
}
//每条记录 的拼接.记录
private void Log(ref System.Text.StringBuilder sb,string format, params object[] args)
{
string tmp = string.Format(format, args);
sb.AppendLine(tmp);
VirtualRemote.Common.Debug(tmp);
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
System.Text.StringBuilder sb = new StringBuilder();
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
IMethodReturn retvalue = getNext()(input, getNext);//在这里执行方法
sw.Stop();
Log(ref sb, "┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓");
Log(ref sb, "┃方法名: {0}",input.MethodBase.Name);
//((Microsoft.Practices.Unity.InterceptionExtension.ParameterCollection)(retvalue.Outputs)).arguments
object value;
for (var i = 0; i < input.Arguments.Count; i++)
{
var arg = input.Arguments.GetParameterInfo(i);
if (arg.IsOut || arg.IsRetval)
{
//if (retvalue.Outputs.ContainsParameter(arg.Name))
value = retvalue.Outputs[arg.Name];
}
else
{
value = input.Arguments[i];
}
Log(ref sb, "┃参数〖{0}.{1}〗= {2}", i, arg.Name, GetObjectString(value));
}
if (retvalue.Exception == null) // retvalue.Exception=null说明函数执行时没有抛出异常
{
var returnvalue = retvalue.ReturnValue;
if (returnvalue != null)
{
Log(ref sb, "┃返回值: {0}", GetObjectString(returnvalue));
}
else
{
Log(ref sb, "┃返回值: {0}","void");
}
}
else
{
Log(ref sb, "★ {0}",retvalue.Exception.ToString());
//retvalue.Exception = null; // 将retvalue.Exception设为null表示异常已经被处理过了,
// 如果不把retvalue.Exception设为null,Unity会再次抛出此异常。
}
Log(ref sb, "┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ 运行时间:{0} 毫秒", sw.ElapsedMilliseconds.ToString());
sb.Insert(0, System.Environment.NewLine);
if (retvalue.Exception == null)
{
VirtualRemote.Common.Info(sb.ToString());
}
else
{
VirtualRemote.Common.Error(sb.ToString());
}
return retvalue;
}
public static string GetObjectString(object value)
{
if (value==null)
{
return "null";
}
if (value is string)
{
}
else if (value.GetType().IsClass)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(value);
}
return value.ToString();
}
}
}
标签:
原文地址:http://www.cnblogs.com/luchaoshuai/p/4793414.html