使用ConfigurationFactory以编程方式配置log4j2

时间:2014-01-02 16:00:14

标签: java logging log4j2

我正在尝试仅使用ConfigurationFactorythis引用来配置和设置Log4j2。我正在使用的代码如下:

public class LoggingConfiguration {

    public static final String PATTERN_LAYOUT = "[%d] [%t] [%-5level] - %msg (%logger{1}:%L) %n%throwable";
    public static final String LOG_FILE_NAME = "app.log";
    public static final String LOG_FILE_NAME_PATTERN = LOG_FILE_NAME + "-yyyy.MM.dd";

    static {
        ConfigurationFactory.setConfigurationFactory(new Log4j2ConfigurationFactory());
    }

    /**
     * Just to make JVM visit this class to initialize the static parts.
     */
    public static void configure() {
    }

    @Plugin(category = "ConfigurationFactory", name = "Log4j2ConfigurationFactory")
    @Order(0)
    public static class Log4j2ConfigurationFactory extends ConfigurationFactory {

        @Override
        protected String[] getSupportedTypes() {
            return null;
        }

        @Override
        public Configuration getConfiguration(ConfigurationSource source) {
            return new Log4j2Configuration();
        }

        @Override
        public Configuration getConfiguration(String name, URI configLocation) {
            return new Log4j2Configuration();
        }

    }

    private static class Log4j2Configuration extends DefaultConfiguration {

        public Log4j2Configuration() {
            setName("app-log4j2");
            String root = System.getProperty("APP_ROOT", "/tmp");
            if (!root.endsWith("/")) {
                root += "/";
            }
                            // MARKER
            Layout<? extends Serializable> layout = PatternLayout.createLayout(PATTERN_LAYOUT, null, null, null, null);

            String oneDay = TimeUnit.DAYS.toMillis(1) + "";
            String oneMB = (1024 * 1024) + "";
            final TimeBasedTriggeringPolicy timeBasedTriggeringPolicy = TimeBasedTriggeringPolicy.createPolicy(oneDay,
                    "true");
            final SizeBasedTriggeringPolicy sizeBasedTriggeringPolicy = SizeBasedTriggeringPolicy.createPolicy(oneMB);
            final CompositeTriggeringPolicy policy = CompositeTriggeringPolicy.createPolicy(timeBasedTriggeringPolicy,
                    sizeBasedTriggeringPolicy);
            final DefaultRolloverStrategy strategy = DefaultRolloverStrategy.createStrategy("7", "1", null,
                    Deflater.DEFAULT_COMPRESSION + "", this);
            Appender appender = RollingFileAppender.createAppender(root + LOG_FILE_NAME, LOG_FILE_NAME_PATTERN, "true",
                    "app-log-file-appender", "true", "true", policy, strategy, layout, null, null, null, null, null);
            addAppender(appender);
            getRootLogger().addAppender(appender, Level.INFO, null);
        }
    }

}

请注意

  • 它扩展了BaseConfiguration默认配置控制台
  • 它尝试将滚动文件追加器添加到根记录器

我得到以下异常:

Exception in thread "main" java.lang.IllegalStateException: Pattern does not contain a date
    at org.apache.logging.log4j.core.appender.rolling.PatternProcessor.getNextTime(PatternProcessor.java:91)
    at org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy.initialize(TimeBasedTriggeringPolicy.java:49)
    at org.apache.logging.log4j.core.appender.rolling.CompositeTriggeringPolicy.initialize(CompositeTriggeringPolicy.java:43)
    at org.apache.logging.log4j.core.appender.rolling.RollingFileManager.<init>(RollingFileManager.java:58)
    at org.apache.logging.log4j.core.appender.rolling.RollingFileManager$RollingFileManagerFactory.createManager(RollingFileManager.java:297)
    at org.apache.logging.log4j.core.appender.rolling.RollingFileManager$RollingFileManagerFactory.createManager(RollingFileManager.java:267)
    at org.apache.logging.log4j.core.appender.AbstractManager.getManager(AbstractManager.java:71)
    at org.apache.logging.log4j.core.appender.OutputStreamManager.getManager(OutputStreamManager.java:65)
    at org.apache.logging.log4j.core.appender.rolling.RollingFileManager.getFileManager(RollingFileManager.java:78)
    at org.apache.logging.log4j.core.appender.RollingFileAppender.createAppender(RollingFileAppender.java:175)
    at com.narmnevis.papyrus.LoggingConfiguration$Log4j2Configuration.<init>(LoggingConfiguration.java:79)
    at com.narmnevis.papyrus.LoggingConfiguration$Log4j2ConfigurationFactory.getConfiguration(LoggingConfiguration.java:55)
    at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:377)
    at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:149)
    at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:85)
    at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:34)
    at org.apache.logging.log4j.LogManager.getContext(LogManager.java:200)
    at org.slf4j.helpers.Log4jLoggerFactory$PrivateManager.getContext(Log4jLoggerFactory.java:104)
    at org.slf4j.helpers.Log4jLoggerFactory.getContext(Log4jLoggerFactory.java:90)
    at org.slf4j.helpers.Log4jLoggerFactory.getLogger(Log4jLoggerFactory.java:46)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:270)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:281)
    at com.narmnevis.papyrus.Main.<init>(Main.java:12)
    at com.narmnevis.papyrus.Main.main(Main.java:21)

如果我在上面的代码中注释掉MARKER之后的代码,它可以工作,但似乎我缺少配置滚动文件appender的东西。我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:7)

log4j 2.x 中,您必须以这种方式指定日期格式

public static final String LOG_FILE_NAME_PATTERN = LOG_FILE_NAME + "-%d{dd-MM-yyy}";
  • %标志着格式的开头
  • d表示它是日期格式(您也可以使用date
  • 在花括号{}中定义格式化程序的选项。在这种情况下,日期格式。您可以使用SimpleDateFormat可以接受的所有内容。

此外,您还可以使用:

  • %d{ABSOLUTE} - &gt; HH:mm:ss,SSS
  • %d{COMPACT} - &gt; yyyyMMddHHmmssSSS
  • %d{DATE} - &gt; dd MMM yyyy HH:mm:ss,SSS
  • %d{ISO8601_BASIC} - &gt; yyyyMMdd HHmmss,SSS
  • %d{ISO8601} - &gt; yyyy-MM-dd HH:mm:ss,SSS

注意:此信息基于log4j 2.0-beta9(当前版本)。由于它是测试版,因此可能略有变化。