順番に従ってメソッド呼び出しをトレースしたいと思います。ロギングはプロダクションに適用されるため、コードをあまり変更したくありません。
これまでのところ、メソッド呼び出しのトレースに Unity のインターセプターを適用したいと考えていましたが、ほぼ完了しました。ただし、ログの出力は期待したものではありません。必要なのは次のとおりです。
以下のpeusedoコードから:
void method1()
{
call method2();
}
トレース ログの形式は次のとおりです。
メソッド呼び出し 1 に入る / メソッド呼び出し 2 に入る
メソッド呼び出し 2 からの離脱 / メソッド呼び出し 1 からの離脱
ところで、私のアプリケーションは .Net フレームワーク バージョン 4 で実行されています。
以下のようなプログラム:
static void Main(string[] args)
{
var container = new UnityContainer();
container.RegisterType<IInterface1, Implementation1>();
container.RegisterType<IInterface2, Implementation2>();
container.RegisterInstance(typeof (IUnityContainer), container);
container.AddNewExtension<Interception>();
container.Configure<Interception>()
.SetInterceptorFor<IInterface1>(new InterfaceInterceptor());
container.Configure<Interception>()
.SetInterceptorFor<IInterface2>(new InterfaceInterceptor());
var service = container.Resolve<IInterface1>();
var results = service.GetListCustomerIdByName("abc");
Console.ReadLine();
}
public interface IInterface1
{
[Trace]
IEnumerable<Guid> GetListCustomerIdByName(string name);
}
public class Implementation1 : IInterface1
{
private readonly IInterface2 _impl;
public Implementation1(IUnityContainer container)
{
_impl = container.Resolve<IInterface2>();
}
public IEnumerable<Guid> GetListCustomerIdByName(string name)
{
return _impl.GetListCustomerIdByName(name);
}
}
public interface IInterface2
{
[Trace]
IEnumerable<Guid> GetListCustomerIdByName(string name);
}
public class Implementation2 : IInterface2
{
public IEnumerable<Guid> GetListCustomerIdByName(string name)
{
yield return Guid.NewGuid();
}
}
public class TraceAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new TraceCallHandler();
}
}
public class TraceCallHandler : ICallHandler
{
public IMethodReturn Invoke(IMethodInvocation input,
GetNextHandlerDelegate getNext)
{
Console.WriteLine("Entering " + input.MethodBase.Name +"()");
InvokeHandlerDelegate next = getNext();
IMethodReturn result = next(input, getNext);
string returnValueStr =
result.ReturnValue == null ? "(void)" : result.ReturnValue.ToString();
if (result.Exception != null)
{
Console.WriteLine("Exception: {0}", result.Exception);
}
Console.WriteLine("Leaving
" +input.MethodBase.Name + "() Return Value: [" + returnValueStr + "]");
return result;
}
public int Order { get; set; }
}
私のコードで申し訳ありません。かなり長いです。