Log4j 2.9.1以编程方式将ThresholdFilter添加到Appender

时间:2017-11-23 11:38:17

标签: java log4j log4j2 configure programmatically

我遇到了log4j 2.9.x的严重问题 我写了#34;认真的"因为log4j的文档是reeeeally垃圾! 此版本没有明确的最新文档。即使现有的文档代码也没有通过编译器,因为它们偶尔会进行更改,您无法确定它们记录的版本。我用Google搜索了一整天,但我发现的内容也大部分都已过时了 所以我有点困惑以编程方式配置log4j2。

我想要实现的目标:

1)额外" loglevel"总是打印到控制台独立于当前的loglevel(类似于gradles LIFECYCLE)

2)登录到控制台和文件

3)在运行时确定的文件名

我找到了一种用XML实现1)和2)的方法。我还没找到适合3)的方法。我不喜欢为文件名使用静态上下文或系统变量,因为我期望并发问题。

因此我的方法是以编程方式配置log4j。这是我的配置工厂:

package my.abc

import org.apache.logging.log4j.Level
import org.apache.logging.log4j.core.Filter
import org.apache.logging.log4j.core.LoggerContext
import org.apache.logging.log4j.core.config.Configuration
import org.apache.logging.log4j.core.config.ConfigurationFactory
import org.apache.logging.log4j.core.config.ConfigurationSource
import org.apache.logging.log4j.core.config.Order
import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder
import org.apache.logging.log4j.core.config.builder.api.LoggerComponentBuilder
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration
import org.apache.logging.log4j.core.config.plugins.Plugin

@Plugin(name = "CustomConfigurationFactory", category = ConfigurationFactory.CATEGORY)
@Order(50)
class CustomConfigurationFactory extends ConfigurationFactory {

    private static String MESSAGE_PATTERN = "%d{HH:mm:ss.SSS} [%t] %-5level 123 %logger{36} - %msg%n"

    Level logLevel
    String packageToScan

    CustomConfigurationFactory(Level logLevel, String packageToScan) {
        this.logLevel = logLevel
        this.packageToScan = packageToScan
    }

    private Configuration createConfiguration(final String name, ConfigurationBuilder<BuiltConfiguration> builder) {
        builder.setConfigurationName(name)
        builder.setStatusLevel(Level.ERROR)

        //add appender
        builder.add(createConsoleAppender(builder))
        builder.add(createLifecycleAppender(builder))

        //add logger
        builder.add(createLogger(builder))

//        builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.DENY)
//                .addAttribute("level", logLevel))

        builder.add(builder.newRootLogger(Level.TRACE).add(builder.newAppenderRef("stdout")))
        return builder.build()
    }

    @Override
    Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
        return getConfiguration(loggerContext, source.toString(), null)
    }

    @Override
    Configuration getConfiguration(final LoggerContext loggerContext, final String name, final URI configLocation) {
        ConfigurationBuilder<BuiltConfiguration> builder = newConfigurationBuilder()
        return createConfiguration(name, builder)
    }

    @Override
    protected String[] getSupportedTypes() {
        return [{ "*" }]
    }

    private AppenderComponentBuilder createConsoleAppender(ConfigurationBuilder<BuiltConfiguration> builder) {
        AppenderComponentBuilder appenderBuilder = builder.newAppender("stdout", "CONSOLE")
        appenderBuilder.add(builder.newLayout("PatternLayout").
                addAttribute("pattern", MESSAGE_PATTERN))
        appenderBuilder.add(builder.newFilter("MarkerFilter", Filter.Result.DENY,
                Filter.Result.NEUTRAL).addAttribute("marker", "lifecycle"))
//        appenderBuilder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT,
//                Filter.Result.DENY).addAttribute("level", logLevel))
        return appenderBuilder
    }

    private AppenderComponentBuilder createLifecycleAppender(ConfigurationBuilder<BuiltConfiguration> builder) {
        AppenderComponentBuilder appenderBuilder = builder.newAppender("lifecycle", "CONSOLE")
        appenderBuilder.add(builder.newLayout("PatternLayout").
                addAttribute("pattern", "%d{HH:mm:ss.SSS} [%t] LIFECYCLE %logger{36} - %msg%n"))
        appenderBuilder.add(builder.newFilter("MarkerFilter", Filter.Result.ACCEPT, Filter.Result.DENY)
                .addAttribute("marker", "lifecycle"))
        return appenderBuilder
    }

    private LoggerComponentBuilder createLogger(ConfigurationBuilder<BuiltConfiguration> builder) {
        builder.newLogger(packageToScan, "trace")
                .add(builder.newAppenderRef("stdout"))
                .add(builder.newAppenderRef("lifecycle"))
                .addAttribute("additivity", false)
    }
}

您可能会注意到2条已注释的行。多数民众赞成我的问题

当我使用builder.add(builder.newFilter("ThresholdFilter"...时,如果日志不符合日志级别,则会过滤掉所有日志。甚至是我想在任何情况下记录的&#34;生命周期&#34; -log。

当我使用时 appenderBuilder.add(builder.newFilter("ThresholdFilter...我收到错误消息2017-11-23 12:12:34,905 main ERROR appender CONSOLE has no parameter that matches element ThresholdFilter

什么是奇怪的。因为当我使用xml配置所有内容时,我可以完全执行该操作(将thresholdfilter添加到单个appender)并且它可以正常工作。

<Appender type="Console" name="STDOUT" >
   <Filters>
      <Filter type="MarkerFilter" marker="lifecycle" onMatch="DENY" onMismatch="NEUTRAL"/>
      <Filter type="ThresholdFilter" level="${logLevel}" onMatch="ACCEPT" onMismatch="DENY" />
   </Filters>
   <Layout type="PatternLayout" pattern="${pattern}"/>
</Appender>

在这里完成整个xml,适用于erequirements 1)和2)

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="info" strict="true" name="XMLConfigTest"
               packages="org.apache.logging.log4j.test">
    <Properties>
        <Property name="logLevel">error</Property>
        <Property name="filename">target/test.log</Property>
        <Property name="pattern">%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Property>
    </Properties>

    <Appenders>
        <Appender type="Console" name="STDOUT">
            <Filters>
                <Filter type="MarkerFilter" marker="lifecycle" onMatch="DENY" onMismatch="NEUTRAL"/>
                <Filter type="ThresholdFilter" level="${logLevel}" onMatch="ACCEPT" onMismatch="DENY"/>
            </Filters>
            <Layout type="PatternLayout" pattern="${pattern}"/>
        </Appender>
        <Appender type="Console" name="LIFECYCLE">
            <Filters>
                <Filter type="MarkerFilter" marker="lifecycle" onMatch="ACCEPT" onMismatch="DENY"/>
            </Filters>
            <Layout type="PatternLayout" pattern="%d{HH:mm:ss.SSS} [%t] LIFECYCLE %logger{36} - %msg%n"/>
        </Appender>
        <Appender type="File" name="File" fileName="${filename}">
            <Layout type="PatternLayout">
                <Pattern>%d %p %C{1.} [%t] %m%n</Pattern>
            </Layout>
        </Appender>
    </Appenders>

    <Loggers>
        <Logger name="my.abc" level="trace" additivity="false">
            <AppenderRef ref="STDOUT"/>
            <AppenderRef ref="LIFECYCLE"/>
        </Logger>

        <Root level="error">
            <AppenderRef ref="STDOUT"/>
        </Root>
    </Loggers>
</Configuration>

必须有一种方法可以将ThresholdFilter添加到appender。我找到了类ThresholdFilter。但我完全不知道如何使用它。实例化作品ThresholdFilter.createFilter(...)但我可以在哪里添加它?

长话短说..

如何在没有xml的情况下将ThresholdFilter添加到单个Appender中?

1 个答案:

答案 0 :(得分:0)

FYI

我解决所有要求的方法:

我切换回XML并添加了一些动态属性。某些属性取自系统属性。如果它们不存在,则将采用定义为xml属性的默认值。

对“logFile”属性进行特殊查看。它是系统属性(用于修复日志文件的路径)和log4j动态确定的混合。这不是真正的线程安全。但在我们的情况下可以接受。

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="info" strict="true" name="XMLConfig"
               packages="org.apache.logging.log4j.test">
    <Properties>
        <Property name="logLevel">INFO</Property>
        <Property name="logFileDir">log/</Property>
        <Property name="logLevelFile">OFF</Property>
        <Property name="logFile">${sys:logFileDir}ConfigMgmt-${date:yyyyMMdd_HHmmss-SSS}.log</Property>
        <Property name="packageName">com.hamburgsud</Property>
        <Property name="messagePattern">%d{HH:mm:ss.SSS} (Test) %-5level %logger{1.} - %msg%n</Property>
    </Properties>

    <Appenders>
        <!-- Console Logging -->
        <Appender type="Console" name="STDOUT">
            <Filters>
                <Filter type="MarkerFilter" marker="lifecycle" onMatch="DENY" onMismatch="NEUTRAL"/>
                <Filter type="ThresholdFilter" level="${sys:logLevel}" onMatch="ACCEPT" onMismatch="DENY"/>
            </Filters>
            <Layout type="PatternLayout" pattern="${sys:messagePattern}"/>
        </Appender>
        <!-- LIFECYCLE is analog to gradles lifecycle log level - means always logging
             When the marker for lifecycle-logging is added, the message will always be logged -->
        <Appender type="Console" name="LIFECYCLE">
            <Filters>
                <Filter type="MarkerFilter" marker="lifecycle" onMatch="ACCEPT" onMismatch="DENY"/>
            </Filters>
            <Layout type="PatternLayout" pattern="%logger{1.} - %msg%n"/>
        </Appender>


        <!-- File Logging -->
        <Appender type="File" name="FILE" fileName="${sys:logFile}" createOnDemand="true">
            <Filters>
                <Filter type="MarkerFilter" marker="lifecycle" onMatch="DENY" onMismatch="NEUTRAL"/>
                <Filter type="ThresholdFilter" level="${sys:logLevelFile}" onMatch="ACCEPT" onMismatch="DENY"/>
            </Filters>
            <Layout type="PatternLayout" pattern="${sys:messagePattern}"/>
        </Appender>
        <!-- Counterpart to consoles LIFECYCLE logging. When file logging is activated and a log is marked with
             lifecycle, the message will be logged to the file too. -->
        <Appender type="File" name="FILELIFECYCLE" fileName="${sys:logFile}" createOnDemand="true">
            <Filters>
                <Filter type="MarkerFilter" marker="lifecycle" onMatch="ACCEPT" onMismatch="DENY"/>
            </Filters>
            <Layout type="PatternLayout" pattern="%logger{1.} - %msg%n"/>
        </Appender>
    </Appenders>

    <Loggers>
        <Root level="trace" additivity="false">
            <AppenderRef ref="STDOUT"/>
            <AppenderRef ref="LIFECYCLE"/>
            <AppenderRef ref="FILE"/>
            <AppenderRef ref="FILELIFECYCLE"/>
        </Root>
    </Loggers>
</Configuration>