如何在依赖注入中使用

如何在依赖注入中使用

本文介绍了如何在依赖注入中使用 log4net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过依赖注入框架找出 log4net 的正确模式和用法.

I'm trying to figure out what the right patter and usage of log4net is with a dependency injection framework.

Log4Net 使用 ILog 接口但需要我调用

Log4Net uses the ILog interface but requires me to call

LogManager.GetLogger(Reflection.MethodBase.GetCurrentMethod().DeclaringType)

在我需要记录信息的每个类或方法中.这似乎违反了 IoC 原则,并使我不得不使用 Log4Net.

in each class or method where I need to log information. This seems to go against IoC principles and couples me to using Log4Net.

我应该以某种方式在某处放置另一层抽象吗?

Should I somehow put in another layer of abstraction somewhere?

此外,我需要像这样记录当前用户名等自定义属性:

Also, I need to log custom properties like the current user name like this:

log4net.ThreadContext.Properties["userName"] = ApplicationCache.CurrentUserName;

我如何封装它,以便我不必每次都记住这样做,并且仍然保持当前记录的方法.我应该做这样的事情还是我完全没有达到目标?

How can I encapsulate this so that I don't have to remember to do it everytime and still maintain the current method that is logging. should I do something like this or am I totally missing the mark?

public static class Logger
{
    public static void LogException(Type declaringType, string message, Exception ex)
    {
        log4net.ThreadContext.Properties["userName"] = ApplicationCache.CurrentUserName;
        ILog log = LogManager.GetLogger(declaringType);
        log.Error(message, ex);
    }
}

推荐答案

我认为您在这里只见树木不见森林.ILog 和 LogManager 是一个轻量级外观,几乎 1:1 等效于 Apache commons-logging,并且实际上不会将您的代码与 log4net 的其余部分耦合.

I think you're not seeing the forest for the trees here. ILog and LogManager are a lightweight façade almost 1:1 equivalent to Apache commons-logging, and do not actually couple your code to the remainder of log4net.

<rant>
I've also found that almost always when someone creates a MyCompanyLogger wrapper around log4net they miss the point badly and will either lose important and useful capabilities of the framework, throw away useful information, lose the performance gains possible using even the simplified ILog interface, or all of the above. In other words, wrapping log4net to avoid coupling to it is an anti-pattern.
</rant>

如果您觉得需要注入它,请通过属性访问记录器实例以启用注入,但以老式方式创建默认实例.

If you feel the need to inject it, make your logger instance accessible via a property to enable injection but create a default instance the old-fashioned way.

至于在每条日志消息中包含上下文状态,您需要添加一个全局属性,其 ToString() 解析为您要查找的内容.例如,对于当前堆大小:

As for including contextual state in every log message, you need to add a global property whose ToString() resolves to what you're looking for. As an example, for the current heap size:

public class TotalMemoryProperty
{
    public override string ToString()
    {
        return GC.GetTotalMemory(false).ToString();
    }
}

然后在启动时插入:

GlobalContext.Properties["TotalMemory"] = new TotalMemoryProperty();

这篇关于如何在依赖注入中使用 log4net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:35