问题
There is now some days that I'm spending on java logger: log4j2 The approach is relatively easy if you decide to work on the basis with an .xml file. But in case you want to create the configuration by code, and adapt through java, it is a bit more complicated.
Below the code I could manage for now. I didn't succeed to reconfigure the log level
Each time depth is stopping on error level
2017-03-15 23:24:27,248 [main] ERROR: This is Logger for 1 Error
2017-03-15 23:24:27,256 [main] ERROR: This is Logger 1 Error
Can you please help to specify how to reload the programmed log4j2 configuration ?
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory;
import org.apache.logging.log4j.core.config.builder.api.LayoutComponentBuilder;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
public class Log4j2Init {
// -------------------------------------------------------
// CONSTRUCTOR
// -------------------------------------------------------
public Log4j2Init() {
}
// -------------------------------------------------------
// TEST
// -------------------------------------------------------
public static void main(String[] args) {
Logger logger;
Log4j2Init log4j2Init = new Log4j2Init();
log4j2Init.addAppenderLogger("./pac-tool.log",Level.ERROR);
logger = LogManager.getLogger(Log4j2Init.class.getName());
logger.info("This is Logger for 1 Info");
logger.error("This is Logger for 1 Error");
logger.debug("This is Logger for 1 Debug");
logger.trace("This is Logger for 1 Trace");
// Reconfiguration of log depth
log4j2Init.addAppenderLogger("./pac-tool.log",Level.TRACE);
logger = LogManager.getLogger(Log4j2Init.class.getName());
logger.info("This is Logger 1 Info");
logger.error("This is Logger 1 Error");
logger.debug("This is Logger 1 Debug");
logger.trace("This is Logger 1 Trace");
}
// -------------------------------------------------------
// METHOD
// -------------------------------------------------------
public void addAppenderLogger(String filename, Level vlevel )
{
ConfigurationBuilder< BuiltConfiguration > builder;
LayoutComponentBuilder layoutBuilder;
AppenderComponentBuilder appenderBuilder;
// Create log4j2 Builder
builder = ConfigurationBuilderFactory.newConfigurationBuilder();
builder.setStatusLevel( Level.INFO);
builder.setConfigurationName("BuilderTest");
// ------------------------------------------
// CONSOLE
// ------------------------------------------
// PatternLayout
layoutBuilder = builder.newLayout("PatternLayout")
.addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable");
// Create Console Appender : Type = "CONSOLE"
appenderBuilder =
builder.newAppender("Stdout", "CONSOLE")
.addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT)
.add(layoutBuilder);
builder.add( appenderBuilder );
// ------------------------------------------
// FILE
// ------------------------------------------
// PatternLayout
layoutBuilder = builder.newLayout("PatternLayout")
.addAttribute("pattern", "%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n");
// Create File Appender : Type = "FILE"
appenderBuilder = builder.newAppender("logfile", "FILE")
.addAttribute("fileName", filename)
.addAttribute("append", "false")
.addAttribute("immediateFlush", "false")
.add(layoutBuilder);
builder.add(appenderBuilder);
// create the new logger
builder.add( builder.newRootLogger( vlevel )
.add( builder.newAppenderRef( "Stdout" ) )
.add( builder.newAppenderRef( "logfile" ) )
);
Configurator.initialize(builder.build());
}
}
Thanks
回答1:
Solution:
import java.nio.file.Paths;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
public class Log4j2Init {
private String logPath;
// -------------------------------------------------------
// CONSTRUCTOR
// -------------------------------------------------------
/**
* Initialize Log4j2
* Configure log path which will be used in "log4j2.xml"
* Common error is caused by the static logger
* If you logs before the System.setProperty, this will cause the variable UNDEFINED error.
* private static final Logger logger = LogManager.getLogger(test.class.getName());
* is forbidden here !!
*/
public Log4j2Init() {
logPath = Paths.get(getUserAppDirectory()+"/Pac-Tool").toString();
System.setProperty("logpath.name",logPath);
}
// -------------------------------------------------------
// TEST
// -------------------------------------------------------
public static void main(String[] args) {
Log4j2Init log4j2Init = new Log4j2Init();
System.out.println("Pat of the Log File : " + log4j2Init.getLogPath());
// Create the Logger
Logger logger = LogManager.getLogger(Log4j2Init.class.getName());
@SuppressWarnings("resource")
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
// Read the Appenders
System.out.println("Appenders declared in .xml :" + loggerConfig.getAppenderRefs());
System.out.println("Appenders used in Logger :" + loggerConfig.getAppenders());
// Apply the level specified in log4j2.xml
System.out.println("Log Level (default in .xml)= " + loggerConfig.getLevel());
logger.error("This is Logger for 1 Error");
logger.info("This is Logger for 1 Info");
logger.debug("This is Logger for 1 Debug");
logger.trace("This is Logger for 1 Trace");
// Remove Console Logger + Set new log level
loggerConfig.removeAppender("Console");
loggerConfig.setLevel(Level.TRACE);
ctx.updateLoggers();
System.out.println("Log Level = " + loggerConfig.getLevel());
System.out.println("Appenders used in Logger :" + loggerConfig.getAppenders());
logger.error("This is Logger 2 Error");
logger.info("This is Logger 2 Info");
logger.debug("This is Logger 2 Debug");
logger.trace("This is Logger 2 Trace");
// Add Appender
Appender appender = config.getAppender("Console");
loggerConfig.addAppender(appender, Level.TRACE, null );
ctx.updateLoggers();
System.out.println("Log Level = " + loggerConfig.getLevel());
System.out.println("Appenders used in Logger :" + loggerConfig.getAppenders());
logger.error("This is Logger 3 Error");
logger.info("This is Logger 3 Info");
logger.debug("This is Logger 3 Debug");
logger.trace("This is Logger 3 Trace");
}
/**
* getUserAppDirectory
* @return
*/
private String getUserAppDirectory() {
String workingDirectory;
String OS = (System.getProperty("os.name")).toUpperCase();
if (OS.contains("WIN"))
{
//it is simply the location of the "AppData" folder
workingDirectory = System.getenv("AppData");
}
else
{
//Otherwise, we assume Linux or Mac
workingDirectory = System.getProperty("user.home");
//if we are on a Mac, we are not done, we look for "Application Support"
workingDirectory += "/Library/Application Support";
}
return workingDirectory;
}
public String getLogPath() {
return logPath;
}
}
回答2:
With .xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- status will define the configuration level of log4j2 configuration file -->
<Configuration status="error" name="XMLPACTOOL">
<Appenders>
<!-- Generate Log in console -->
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n" />
</Console>
<!-- Generate Log in file -->
<File name="LogFile" fileName="${sys:logpath.name}/Pac-Tool.log"
immediateFlush="false" append="false">
<PatternLayout
pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</File>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console" />
<AppenderRef ref="LogFile" />
</Root>
</Loggers>
</Configuration>
来源:https://stackoverflow.com/questions/42828748/how-to-reload-a-programmed-log4j2-configuration-in-java