如何在log4j中集成编程配置?

时间:2018-05-08 13:46:47

标签: java logging log4j2 rollingfileappender programmatic-config

我正在使用Log4j版本2.0.1版本,并且由于组织策略,我暂时不能使用任何更高版本。

group:'org.apache.logging.log4j',name:'log4j-core',version:'2.0.1'
group:'org.apache.logging.log4j',name:'log4j-api',version:'2.0.1'

我的记录要求

  1. 如果customDebug = true作为环境变量,则启用调试日志记录
  2. 应该生成2个日志文件 - 一个主要日志记录(基于以上日志的信息/调试)和错误日志记录。
  3. 制定基于尺寸的滚动策略
  4. 日志文件的目录是动态的。
  5. 格式应该带有特定样式的时间和线程ID。
  6. 我尝试以下列方式实现log4j的编程配置 -

    CustomConfigFactory.java>>

    @Plugin(name = "CustomConfigFactory", category = "JsonConfigurationFactory")
    @Order(10)
    public class CustomConfigFactory extends JsonConfigurationFactory {
    
        @Override
        public String[] getSupportedTypes() {
            return new String[] {".json"};
        }
    
        @Override
        public Configuration getConfiguration(ConfigurationSource cs) {
            try{
                String file = Thread.currentThread().getContextClassLoader().getResource("customRollingConfiguration.json").getFile()
                cs = new ConfigurationSource(new FileInputStream(new File(file ));
            } catch (Exception e){
                System.err.println("ERROR : Exception encountered while initiating configuration source: "+e);
            }
            return new CustomJsonConfiguration(cs);
        }
    
    }
    

    CustomJsonConfiguration.java>>

    public class CustomJsonConfiguration extends JsonConfiguration {
    
        public CustomJsonConfiguration(final ConfigurationSource configSource) {
            super(configSource);
        }
    
        @Override
        protected void doConfigure(){
            try {
                ConfigurationSource source = this.getConfigurationSource();
                Configuration config = CustomConfigFactory.getInstance().getConfiguration(source);
    
                final Layout layout = PatternLayout.createLayout("%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p [%5T] %c{1}:%L - %m%n",
                    config,null,Charset.defaultCharset(),true,false,"","");
    
                SizeBasedTriggeringPolicy policy = SizeBasedTriggeringPolicy.createPolicy("10 MB");
                DefaultRolloverStrategy strategy = DefaultRolloverStrategy.createStrategy("50", "5", "min", "9", config);
    
                String logDir = System.getenv("log_dir");
                String primaryLogFile = logDir+"/my_main_log";
                String primaryLogFilePattern = primaryLogFile+"-backup-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz";
    
                String errorLogFile = logDir+"/my_err_log";
                String errorLogFilePattern = errorLogFile+"-backup-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz";
    
                RollingFileAppender appender1 = RollingFileAppender.createAppender(primaryLogFile,
                    primaryLogFilePattern,"true", "debugFile","true", "false","false",
                    policy, strategy, layout, null, null, null, null, config);
                appender1.start();;
    
                RollingFileAppender appender2 = RollingFileAppender.createAppender(errorLogFile,
                    errorLogFilePattern,"true","errorFile","true","false","false",
                    policy, strategy, layout, null,null,null,null, config);
                appender2.start();;
    
                config.addAppender(appender1);
                config.addAppender(appender2);
    
                LoggerConfig primaryLoggerConfig = null;
                if(Boolean.valueOf(System.getenv("customDebug")){
                     primaryLoggerConfig = new LoggerConfig("aa.bb.cc.dd",Level.DEBUG,false);
                } else {
                    primaryLoggerConfig = new LoggerConfig("aa.bb.cc.dd",Level.INFO,false);
                }
                LoggerConfig errorLoggerConfig = new LoggerConfig("aa.bb.cc.dd",Level.ERROR,false);
    
                primaryLoggerConfig.addAppender(appender1,null,null);
                errorLoggerConfig.addAppender(appender2,null,null);
                config.addLogger("aa.bb.cc.dd",primaryLoggerConfig);
                config.addLogger("aa.bb.cc.dd",errorLoggerConfig);
    
                LoggerContext context = new LoggerContext("default_context");
                context.start(config);
            } catch (Exception e){
                System.err.println("");
            }
        }
    

    其中aa.bb.cc.dd引用下面MyClass的包名。

    MyClass.java 将使用此记录器>>

    package aa.bb.cc.dd;
    
    public MyClass {
        static final Logger myCustomLog = LogManager.getLogger(MyClass.class);
    
        void doSomething(){
            myCustomLog.info("Doing something");
        }
    }
    

    样本测试方法作为测试上述类>>>

    的testng类的一部分
    @Test
    public void testDoingSomething(){
        MyClass m1 = new MyClass();
        m1.doSomething();
    }
    

    但是上面似乎没有用,并且没有生成任何日志文件,即日志记录不起作用。 我主要提到了这个实现 - https://logging.apache.org/log4j/2.x/manual/customconfig.html#Hybrid

    如果有人能帮我解决这个问题,我会很感激。欢迎所有建议!!!

    提前致谢。

    编辑>>> 以下是结合@VikasSachdeva评论后的配置json。即使在my_main.log

    中记录了ERROR条件,错误文件仍为空
    {
      "configuration": {
         "name": "RollingKitConfig",
        "Appenders": {
      "appender": [
        {
          "type": "RollingFile",
          "name": "debugFile",
          "fileName": "${env:log_dir}/my_main_log",
          "filePattern": "${env:log_dir  }/my_main_backup-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz",
          "PatternLayout": {
            "pattern": "%d{yyyy-MM-dd HH:mm:ss,nnn} [%-5p] [%5t] [%c{3}:%L] - %m%n"
          },
          "Policies": {
            "SizeBasedTriggeringPolicy": {
              "size": "10 MB"
            }
          },
          "DefaultRolloverStrategy": {
            "max": "10"
          },
          "ThresholdFilter": {
            "level": "${env:customDebug:-info}"
          }
        },
        {
          "type": "RollingFile",
          "name": "errorFile",
          "fileName": "${env:log_dir}/errors.log",
          "filePattern": "${env:log_dir}/errors_backup-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz",
          "PatternLayout": {
            "pattern": "%d{yyyy-MM-dd HH:mm:ss,nnn} [%-5p] [%5t] [%c{1}:%L] - %m%n"
          },
          "Policies": {
            "SizeBasedTriggeringPolicy": {
              "size": "10 MB"
            }
          },
          "DefaultRolloverStrategy": {
            "max": "10"
          },
          "ThresholdFilter": {
            "level": "ERROR",
            "onMatch": "ACCEPT",
            "onMisMatch": "DENY"
          }
        }
      ]
    },
    "Loggers": {
      "logger": [
        {
          "name": "KitLogger",
          "level": "info",
          "additivity": "false",
          "AppenderRef": [
            {
              "ref": "debugFile"
            },
            {
              "ref": "errorFile"
            }
          ]
        }
      ],
      "root": {
        "level": "debug",
        "appender-ref": {
          "ref": "debugFile"
        }
      }
    }
      }
    }
    

1 个答案:

答案 0 :(得分:1)

如果您只想使用环境变量选择日志文件位置,则可以单独使用配置文件执行此操作,如log4j2 documentation

中所述

考虑您的环境变量为log_dir=D:/logs/。然后您可以更改您的配置,如下所示 -

{
    "configuration": {
        "name": "RollingConfig",
        "ThresholdFilter": { "level": "info" },
        "properties": {
            "property": {
                "name": "basePath",
                "value": "${env:log_dir}"
             }
        },
        "appenders": {
            "RollingFile": {
                "name": "debugFile",
                "fileName": "${basePath}my_main.log",
                "filePattern": "${basePath}my_main_%d{yyyyMMdd}.log.gz",
                "PatternLayout": { "pattern": "%d{yyyy-MM-dd HH:mm:ss} %-5p [%5T] %c{1}:%L - %m%n" },
                "Policies": {
                    "SizeBasedTriggeringPolicy": { "size": "10 MB" }
                },
               "DefaultRolloverStrategy": { "max": "10"  }
            },
            "RollingFile": {
                "name": "errorFile",
                "fileName": "${basePath}my_err.log",,
                "filePattern": "${basePath}my_err_%d{yyyyMMdd}.log.gz",
                "thresholdFilter": {
                    "level": "ERROR",
                    "onMatch": "ACCEPT",
                    "onMisMatch": "DENY"
                },
                "PatternLayout": { "pattern": "%d{yyyy-MM-dd HH:mm:ss} %-5p [%5T] %c{1}:%L - %m%n" },
                "Policies": {
                     "SizeBasedTriggeringPolicy": {  "size": "10 MB" }
                },
                "DefaultRolloverStrategy": {"max": "10"}
            }
        },
        "loggers": {
            "logger": {
                 "name": "mainLogger",
                 "level": "info",
                 "additivity": "false",
                 "appender-ref": [ 
                                 {"ref": "debugFile"}, 
                                 { "ref":"errorFile"}
                                 ]
            },
            "root": {
                "level": "info",
                 "appender-ref": [ 
                                 {"ref": "debugFile" }, 
                                 { "ref":"errorFile" }
                                 ]
             }
          }
       }
}