package com.x.server.console.log;

import java.io.PrintStream;

import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.OutputStreamAppender;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.slf4j.LoggerFactory;

public class Log4j2Configuration {

	private Log4j2Configuration() {

	}

	private static final String CONVERSION_PATTERN = "%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c - %m%n";

	public static void reconfigure() {

		final PrintStream stderr = System.err;
		final PrintStream stdout = System.out;

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

		addStandardOutAppender(config, stdout);

		bypassErr(stderr);
		bypassOut(stdout);

		context.updateLoggers();
	}

	private static void addStandardOutAppender(final Configuration config, final PrintStream stdout) {
		final PatternLayout layout = PatternLayout.newBuilder().withConfiguration(config)
				.withPattern(CONVERSION_PATTERN).build();
		final Appender appender = OutputStreamAppender.createAppender(layout, null, stdout, "stdout", true, true);
		appender.start();
		config.addAppender(appender);
		config.getRootLogger().addAppender(appender, null, null);
	}

	private static void bypassErr(final PrintStream stderr) {
		BypassLoggerPrintStream printStream = new BypassLoggerPrintStream(stderr,
				LoggerFactory.getLogger("System.err"));
		System.setErr(printStream);
	}

	private static void bypassOut(final PrintStream stdout) {
		BypassLoggerPrintStream printStream = new BypassLoggerPrintStream(stdout,
				LoggerFactory.getLogger("System.out"));
		System.setOut(printStream);
	}

}

@@ -55,16 +55,38 @@
 tStream;
+%0Aimport java.util.Map;
 %0A%0Aimport
@@ -305,16 +305,74 @@
 ration;%0A
+import org.apache.logging.log4j.core.config.LoggerConfig;%0A
 import o
@@ -1091,16 +1091,257 @@
 dout) %7B%0A
+%09%09final LoggerConfig rootLogger = config.getRootLogger();%0A%09%09final Map%3CString, Appender%3E appenders = rootLogger.getAppenders();%0A%09%09//System.out.println(%22log4j appenders: %22 + appenders);%0A%09%09if  (appenders.containsKey(%22stdout%22)) %7B%0A%09%09%09return;%0A%09%09%7D%0A
 %09%09final 
@@ -1625,27 +1625,17 @@
 der);%0A%09%09
-config.getR
+r
 ootLogge
@@ -1635,18 +1635,16 @@
 otLogger
-()
 .addAppe

支持log4j stdout appender 外部可配置