Log4j2 - 将日志写入 Writer

Log4j2 - Write Logs to Writer

Log4j 中有一个 WriterAppender 可以将日志写入 Writer

我需要 Log4j2 中的相同功能,但我还没有找到执行此操作的选项。有谁知道如何用 Log4j2 达到同样的效果?

如果没有满足您需求的现有 appender,请创建自定义 appender 插件。

我整理了一个简单的例子。

package com.logging;

import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginElement;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.layout.PatternLayout;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.Writer;

@Plugin(name = "WriterAppender", category = "Core", elementType = "appender", printObject = false)
public class WriterAppender extends AbstractAppender{

    private Writer writer;

    protected WriterAppender(String name, Filter filter, Layout<? extends Serializable> layout, boolean ignoreExceptions, String argOne, String argTwo) {
        super(name, filter, layout, ignoreExceptions);
        writer = new PrintWriter(System.out);//init or retrieve writer resource upon construction
    }

    @Override
    public void append(LogEvent logEvent) {
        try {
            writer.write(logEvent.getMessage().getFormattedMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PluginFactory
    public static WriterAppender createAppender(
            @PluginAttribute("name") String name,
            @PluginElement("Layout") Layout<? extends Serializable> layout,
            @PluginElement("Filter") final Filter filter,
            @PluginAttribute("otherAttribute") String otherAttributeOne,
            @PluginAttribute("otherAttributeTwo") String otherAttributeTwo
    ) {
        if (name == null) {
            LOGGER.error("No name provided for MyCustomAppenderImpl");
            return null;
        }
        if (layout == null) {
            layout = PatternLayout.createDefaultLayout();
        }
        return new WriterAppender(name, filter, layout, true, otherAttributeOne,otherAttributeTwo);
    }
}

您将使用配置来添加 WriterAppender,就像添加任何其他附加程序一样。

虽然这是一个老问题,但我想添加答案以备将来参考。

WriterAppender 出现在 log4j2 中。下面是使用编程配置配置它的一种方法 -

package example;

import java.io.StringWriter;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.WriterAppender;
import org.apache.logging.log4j.core.config.AppenderRef;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.layout.PatternLayout;

public class App {

    private static final Logger LOGGER = LogManager.getLogger(App.class);

    private static StringWriter stringWriter = new StringWriter();

    public static void main(String[] args) {
        createLogger();
        LOGGER.info("It is info log -  {}", i);
        LOGGER.warn("It is warn log - {} ", i);
        LOGGER.error("It is error log");

        System.out.println(stringWriter.toString());

    }

    private static void createLogger() {

        final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        final Configuration config = ctx.getConfiguration();

        PatternLayout layout = PatternLayout.newBuilder()
                .withPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] - %msg%n").build();

        WriterAppender writerAppender = WriterAppender.newBuilder().setName("writeLogger").setTarget(stringWriter)
                .setLayout(layout).build();
        writerAppender.start();
        config.addAppender(writerAppender);

        AppenderRef ref = AppenderRef.createAppenderRef("writeLogger", null, null);
        AppenderRef[] refs = new AppenderRef[] { ref };

        LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "example", null, refs, null, config,
                null);

        loggerConfig.addAppender(writerAppender, null, null);
        config.addLogger("example", loggerConfig);
        ctx.updateLoggers();
    }
}