package foundation.log; import java.io.File; import java.io.FileInputStream; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.appender.FileAppender; import org.apache.logging.log4j.core.config.AppenderRef; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.ConfigurationSource; import org.apache.logging.log4j.core.config.Configurator; import org.apache.logging.log4j.core.config.LoggerConfig; import org.apache.logging.log4j.core.layout.PatternLayout; public class LogCenter { private static LoggerContext context; private static Configuration configuration; public static void initConsole(String path) throws Exception { File file = new File(path); if (!file.exists()) { throw new Exception("log config not exists: " + file); } FileInputStream inputStream = new FileInputStream(file); try { ConfigurationSource source = new ConfigurationSource(inputStream); context = Configurator.initialize(null, source); configuration = context.getConfiguration(); } finally { inputStream.close(); } } @SuppressWarnings({ "rawtypes", "unchecked" }) public static void appendOneLogger() { Layout layout = PatternLayout.createDefaultLayout(configuration); @SuppressWarnings("deprecation") Appender appender = FileAppender.createAppender("target/test.log", "false", "false", "File", "true", "false", "false", "4000", layout, null, "false", null, configuration); appender.start(); configuration.addAppender(appender); AppenderRef ref = AppenderRef.createAppenderRef("File", null, null); AppenderRef[] refs = new AppenderRef[] {ref}; LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.DEBUG, "org.apache.logging.log4j", "true", refs, null, configuration, null); loggerConfig.addAppender(appender, null, null); configuration.addLogger("org.apache.logging.log4j", loggerConfig); context.updateLoggers(); } }