当前位置: 首页 > 知识库问答 >
问题:

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

屠君墨
2023-03-14

现在我花了几天时间在java logger:log4j2上。如果您决定使用一个java logger,那么这种方法相对容易。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个答案

微生毅
2023-03-14

具有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>
巫马修为
2023-03-14

解决方案:

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

}

 类似资料:
  • 问题内容: 我将log4j2.xml配置文件设置为每30秒检查一次: 是否可以以编程方式告诉log4j2检查配置中的更改而不是超时? 注意: 我不想以编程方式加载指定配置文件的配置,我只想告诉log4j2检查MonitorInterval过期之前已加载的配置文件。 谢谢! 问题答案: 看来我找到了解决方案: 有人看到任何错误/副作用吗?

  • 问题内容: 我知道有一个reloadDefaultConfiguration()jmx操作,但是没有获取MBean实例并调用此操作,是否有一个Logback api重新加载默认配置(可以选择指定日志配置文件路径)? 问题答案: 这是以下代码的源代码: 只在需要的地方运行此代码呢? 唯一的问题是变量。您可以使用以下方法获取它: 不幸的是,似乎没有完善的API可以做到这一点,那么引发问题呢?您是否还知

  • 问题内容: 我想以编程方式从应用程序中加载Log4j2 XML配置文件。 试过这个: 还有这个: 但是什么都没有。 问题答案: 自己找到答案。有人可能会觉得有用。

  • 我在我的应用程序中使用导航栏,每次我选择一个项目时,它都会加载一个片段。 我能够使用相同的文本字段和按钮保存片段的状态,但有一个片段可以加载地图、添加标记、集群并执行。 每次我转到另一个菜单项并返回时,它都会重新加载所有内容,例如AsyncTask、Cluster、Markers。我如何停止此片段以不再重新创建地图并在返回时保存状态: Udate 1:我更新了代码,但问题仍然存在 主要活动: 主片

  • 你能帮我找出配置中缺少的步骤吗? 我正试图将logger添加到我非常简单的web应用程序中:为了做到这一点,我使用了log4j2 (beta9)。 我写下了我的<code>log4j2.xml<code>如下 我把它放在WEB-INF文件夹里。 然后,我有一个简单的servlet,它执行以下操作 正如你所看到的,这只是一个尝试,看看是否如预期的那样工作,但它没有。通过阅读此处的web app,我不

  • 我正在将一些web应用程序从log4j1.12迁移到Log4j2。由于公司政策,我们的log4j。xml文件位置在应用服务器中配置为URL,应用程序必须使用JNDI获取它们。我们实现了一个,它允许我们以这种方式初始化log4j基础结构: 但是,随着log4j2api的更改,这将无法再使用。Log4j2提供了lo4j2web。jar模块,它使用初始化库。这将调用,负责获取配置文件的URI。 有什么方