开发者

Inject logging dependency with Castle Windsor

开发者 https://www.devze.com 2023-03-28 07:26 出处:网络
I was trying to inject logging dependency by Castle Windsor to my code. More precisely, whenever a method in a class throws an error or application flow enters into a method it simply logs into a file

I was trying to inject logging dependency by Castle Windsor to my code. More precisely, whenever a method in a class throws an error or application flow enters into a method it simply logs into a file. How to do this by writing nothing like

logger.Debug("Error code");

in the methods explicitly for each of the methods. Suppose we add attribute on each of the class or methods to leverage the logging facility for 开发者_StackOverflow社区that.

Thanks in advance.


Use the interceptor facility in Castle Windsor.

So mark your class with

[Interceptor(typeof(UnhandledExceptionLogger))]

and create a class UnhandledExceptionLogger that implements IInterceptor. Roughly:

public void Intercept(IInvocation invocation) {
    try {                
        invocation.Proceed();
    }
    catch (Exception e) {
        // log the exception e
        throw;
    }
}

and then when Castle Windsor creates an instance of your class marked with this Interceptor, it will create a proxy that wraps all methods invocations in the above try/catch log/rethrow block.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号