本文介绍了Castle:如何在日志拦截器中获取正确的ILogger?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您在Castle Windsor中使用LoggingFacility,则如果您的班级中具有可选的记录器依赖项(Castle可以将记录器注入到的ILogger属性),则容器将自动解析与您的班级关联的记录器,但是我如何利用我是否想使用AOP(拦截器方法)实现日志记录?我基本上想写这样的东西:

If you are using the LoggingFacility in Castle Windsor the container will automatically resolve the logger associated with your class if you have optional logger dependencies in your class (an ILogger property that castle can inject the logger into), but how can I leverage the facility if I want to implement the logging using AOP (interceptor approach)? I basically want to write something like:

    public void Intercept(IInvocation invocation)
    {
        ILogger logger = LogManager.GetLogger(invocation.TargetType);
        //..
    }

但是没有LogManager可以说在城堡框架中。解决此问题的最佳方法是什么?我应该忽略设施方法,直接在拦截器中使用log4net吗?

But there is no LogManager to speak of in the Castle framework. What is the best approach to solving this? Should I just ignore the facility approach and use log4net directly in the interceptor?

推荐答案

对Castle.Core.Logging产生依赖性。构造函数中的ILoggerFactory,并使用Intercept方法在工厂中创建记录器

Take a dependency on Castle.Core.Logging.ILoggerFactory in your constructor and create the logger from the factory in the Intercept method

public class LoggingInterceptor : IInterceptor
{
    readonly ILoggingFactory loggingFactory;

    public LoggingInterceptor(ILoggingFactory loggingFactory)
    {
        this.loggingFactory = loggingFactory;
    }

    public void Intercept(IInvocation invocation)
    {
        ILogger logger = loggingFactory.Create(invocation.TargetType);
        //..
    }
}

这篇关于Castle:如何在日志拦截器中获取正确的ILogger?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 19:12