Log4j2 - Write Logs to Writer

情到浓时终转凉″ 提交于 2019-12-10 23:33:31

问题


In Log4j there was a WriterAppender that made it possible to write the logs to a Writer.

I need the same functionality in Log4j2, but I haven't found an option to do this yet. Does anyone know how to achieve the same with Log4j2 ?


回答1:


If there is not an existing appender that serves your needs, create a custom appender plugin.

I put together a quick example.

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);
    }
}

You would use the configuration to add the WriterAppender as you would any other appender.




回答2:


Although this is an old question, I would like to add answer for future reference.

WriterAppender is present in log4j2. Below is one way to configure it using programmatic configuration -

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();
    }
}


来源:https://stackoverflow.com/questions/33603750/log4j2-write-logs-to-writer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!