简体   繁体   English

使用 Castle Windsor 注入日志记录依赖项

[英]Inject logging dependency with Castle Windsor

I was trying to inject logging dependency by Castle Windsor to my code.我试图将 Castle Windsor 的日志依赖注入到我的代码中。 More precisely, whenever a method in a class throws an error or application flow enters into a method it simply logs into a file.更准确地说,每当 class 中的方法抛出错误或应用程序流进入方法时,它都会简单地登录到文件中。 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 that.假设我们在每个 class 或方法上添加属性以利用日志工具。

Thanks in advance.提前致谢。

Use the interceptor facility in Castle Windsor.使用温莎城堡的拦截设施

So mark your class with所以标记你的 class

[Interceptor(typeof(UnhandledExceptionLogger))]

and create a class UnhandledExceptionLogger that implements IInterceptor .并创建一个实现IInterceptor的 class UnhandledExceptionLogger 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.然后当 Castle Windsor 创建标记有此Interceptor的 class 的实例时,它将创建一个代理,将所有方法调用包装在上述 try/catch 日志/重新抛出块中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM