如何在java中重新加载编程的log4j2配置

时间:2017-03-16 08:26:18

标签: java log4j2

现在有些日子我花在java logger上:log4j2 如果您决定使用.xml文件进行工作,则该方法相对容易。 但是如果你想通过代码创建配置,并通过java进行调整,那就有点复杂了。

我现在可以管理的代码下面。 我没有成功重新配置日志级别

每次深度都在错误级别停止

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 

您能帮忙指定如何重新加载编程的log4j2配置吗?

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


    }

}

由于

2 个答案:

答案 0 :(得分:1)

解决方案:

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

}

答案 1 :(得分:0)

使用.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>