Castle:如何在日志拦截器中获取正确的 ILogger?

发布于 2024-10-03 23:44:03 字数 385 浏览 1 评论 0原文

如果您在温莎城堡中使用 LoggingFacility,如果您的类中有可选的记录器依赖项(城堡可以将记录器注入其中的 ILogger 属性),容器将自动解析与您的类关联的记录器,但是如果我想使用AOP(拦截器方法)来实现日志记录?我基本上想写这样的东西:

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

但是Castle框架中没有LogManager可言。解决这个问题的最佳方法是什么?我应该忽略工具方法并直接在拦截器中使用 log4net 吗?

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);
        //..
    }

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

君勿笑 2024-10-10 23:44:03

在构造函数中依赖 Castle.Core.Logging.ILoggerFactory 并在 Intercept 方法中从工厂创建记录器

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);
        //..
    }
}

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);
        //..
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文