简体   繁体   English

启用日志记录到log4net中的两个不同位置

[英]Enable logging to two different locations in log4net

I'm brand new to log4net, and I'm trying to maintain some legacy code that uses it. 我是log4net的新手,我正在尝试维护一些使用它的旧代码。 I've noticed that having two static classes that tell log4net to log to different locations are tripping over each other. 我注意到,有两个告诉Log4net记录到不同位置的静态类正在相互跳闸。

The classes each have a static constructor that looks like this 每个类都有一个静态构造函数,如下所示

static Logger() {
    _Logger = new X.LoggingService.AppLogger(
                X.UtilityServer.Configuration.ConfigInfo.LoggerConfigFile);
}

except with different config values; 除非具有不同的配置值; both of these static classes are initializing the same AppLogger helper class. 这两个静态类都正在初始化相同的AppLogger帮助器类。 The second class to initialize is overwriting the initialization of the first. 要初始化的第二个类将覆盖第一个类的初始化。 I think I've tracked the problem down to here: 我想我已经将问题归结为:

private  ILog Log  {
    get {
        if (!_ConfiguratorSet) {
            _ConfiguratorSet = true;
            XmlConfigurator.Configure(new FileInfo(_ConfigFile)); //<--- STATIC
        }
        return _log; 
    }
}

Since I absolutely do not have to support thread safety , should I just get remove the if statement? 由于我绝对不必支持线程安全 ,因此是否应该删除if语句? Would calling XmlConfigurator.Configure every time I need to log something be prohibitively expensive? 每次需要登录某些东西时,都将调用XmlConfigurator.Configure昂贵吗? Is there a better way? 有没有更好的办法? This code was written using log4net version 1.2.10 该代码是使用log4net版本1.2.10编写的

Ideally, what shall be happening is: 理想情况下,将发生以下情况:

  1. Configure log4net (do this once at app start up - this is very slow) 配置log4net(在应用启动时执行一次 -这非常慢)
  2. Use dependency injection to pass ILog to the classes (better) or service locator (worse) to get the ILog in the needed class 使用依赖注入将ILog传递给类(更好) 服务定位器(更差),以在所需类中获取ILog
  3. One configuration can provide you with multiple loggers, which in turn can have multiple appenders that can log to various outputs (db, console, queues etc.) This gives you a lot of flexibility governed by one config file. 一种配置可以为您提供多个记录器,而记录器又可以具有多个附加器,这些附加器可以记录到各种输出(数据库,控制台,队列等)。这为您提供了由一个配置文件控制的大量灵活性。 You can have one config file with two file loggers with different names that will use two different appenders to output data, well, into two files. 您可以拥有一个配置文件,其中两个文件记录器的名称不同,它们将使用两个不同的附加程序将数据输出到两个文件中。

The code 编码

private  ILog Log  {
    get {
        if (!_ConfiguratorSet) {
            _ConfiguratorSet = true;
            XmlConfigurator.Configure(new FileInfo(_ConfigFile)); //<--- STATIC
        }
        return _log;
    }
}

is really confusing and wrong. 确实令人困惑和错误。 You should only return a log there, so no ifs at all. 您应该只返回一个日志在那里,所以没有如果可言。 It is a violation of single responsibility principle and possibly the reason of the bug you see. 这违反了单一责任原则,并且可能是您看到错误的原因。

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

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