Log4j2计算消息

时间:2016-05-23 18:37:06

标签: java log4j2

我想算一下我的信息。因此,日志消息应如下所示:

000001:Test:Service:23-05-2016:20-26-01:Message
000002:Test:Service:23-05-2016:20-26-01:Message
000003:Test:Service:23-05-2016:20-26-01:Message

我使用以下log4j2.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="OFF">
    <Appenders>
        <File name="logFile" filename="${sys:logDir}${sys:logFilename}">
            <PatternLayout pattern="${sys:logLevel}:Service:%d{dd-MM-yyyy:HH-mm-ss}:%msg%n" />
        </File>
    </Appenders>
    <Loggers>
        <Root level="${sys:logLvl}">
            <AppenderRef ref="logFile" />
        </Root>
    </Loggers>
</Configuration>

我找不到任何东西。对于新日志文件的翻转,只有%i的内容。我希望有人可以帮助我!

请注意

编辑:

我可以解决问题。感谢Carlitos Way和rgoers:

我的新类SequenceNumberPatternConverterPaddedWithZeros:

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.pattern.ConverterKeys;
import org.apache.logging.log4j.core.pattern.LogEventPatternConverter;

import java.util.concurrent.atomic.AtomicLong;

@Plugin(
        name = "SequenceNumberPaddedPatternConverter",
        category = "Converter"
)
@ConverterKeys({"snp", "sequenceNumberPadded"})
public final class SequenceNumberPatternConverterPaddedWithZeros extends LogEventPatternConverter {
    private String zeros;
    private static final AtomicLong SEQUENCE = new AtomicLong();

    private SequenceNumberPatternConverterPaddedWithZeros(String zeros) {

        super("Sequence Number Padded", "snp");
        this.zeros = zeros;
    }

    public static SequenceNumberPatternConverterPaddedWithZeros newInstance(String[] options) {
        if(options.length > 1 ||!StringUtils.isNumeric(options[0])) {
            LOGGER.error("Incorrect option on SequenceNumberPatternConverterPadded. Expected a number, received " + options.length);
            return null;
        }
        return new SequenceNumberPatternConverterPaddedWithZeros(options[0]);//INSTANCE;
    }

    public void format(LogEvent event, StringBuilder toAppendTo) {
        toAppendTo.append(String.format("%0"+this.zeros+"d",SEQUENCE.incrementAndGet()));
    }
}

所以现在你可以像这样使用它:

<PatternLayout pattern="%snp{6}:${sys:logLevel}:Service:%d{dd-MM-yyyy:HH-mm-ss}:%msg%n"/>

000010:Test:Service:24-05-2016:11-06-52:message

1 个答案:

答案 0 :(得分:2)

我相信log4j没有你想要的内置功能......所以,恕我直言,你最好的选择是:

  1. 使用log4j内置MDC功能并通过JAVA代码生成您自己的消息序列(序列生成器必须实现为同步单例)...稍后,您应该将模式重新配置为: %X{seqNextVal}${sys:logLevel}:Service:%d{dd-MM-yyyy:HH-mm-ss}:%msg%n"其中seqNextVal已配置的邮件序列(例如:MDC.put(seqNextVal, MessageSequenceGen.nextValue())

  2. 定义您自己的Appender(或PatternLayout),其中包含(并隐藏)消息序列生成器逻辑。我相信这是最难但最好的选择,因为你在logj4组件中封装了序列的逻辑,你不需要在任何地方修改代码......

  3. 请注意,无论您的工具是什么解决方案,请记住以某种方式保留您的序列...否则,当您的应用程序再次启动时,消息计数也将在“一”重新启动...

    更新:检查log4j文档,我发现:log4j layouts ...在模式部分查找sequenceNumber ...可能这可以帮到你......