在运行时更新log4j2模式

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在运行时更新log4j2模式相关的知识,希望对你有一定的参考价值。

我搜索得很长很难,所以在将它标记为重复之前请先阅读。

我有一个函数(Lambda.handle()),用param id调用。我想将该id添加到每个日志消息作为前缀。它会在每次调用函数时发生变化。所以我想更新记录器模式以将此id添加为前缀。

我读了:

以下代码基于log4j2文档。它打印:

INIT  MyLogger handle() - id ONE 
INIT  MyLogger handle() - id TWO 
INIT  MyLogger handle() - id THR 

如果我注释掉行initLoggerConfig("INIT ");然后打印:

ERROR StatusLogger No Log4j 2 configuration file found. Using default configuration (logging only errors to the console), or user programmatically provided configurations. Set system property 'log4j2.debug' to show Log4j 2 internal initialization logging. See https://logging.apache.org/log4j/2.x/manual/configuration.html for instructions on how to configure Log4j 2
ONE  MyLogger handle() - id ONE 
ONE  MyLogger handle() - id TWO 
ONE  MyLogger handle() - id THR 

我想要它打印:

ONE  MyLogger handle() - id ONE 
TWO  MyLogger handle() - id TWO 
THR  MyLogger handle() - id THR 

我是否评论ctxLocal = ctx;,没有任何影响。

这是the full log我通过将log4j自己的日志记录级别设置为ALL(builder.setStatusLevel(Level.ALL);

这是代码

package foobar;

import java.util.Arrays;
import java.util.List;

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.Filter;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.config.AppenderRef;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.LoggerConfig;
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.impl.BuiltConfiguration;
import org.apache.logging.log4j.core.layout.PatternLayout;

class Lambda {
  private static final String LOGGER_NAME = "MyLogger";
  private LoggerContext ctx;

  public Lambda() {
    initLoggerConfig("INIT ");
  }

  public void handle(String id) {
    updateLoggerConfig(id);
    Logger logger = LogManager.getLogger(LOGGER_NAME);
    logger.error("handle() - id {}", id);
  }

  private void updateLoggerConfig(String prefix) {
    final LoggerContext ctxLocal = (LoggerContext) LogManager.getContext(false);
    // ctxLocal = ctx;
    Configuration config = ctxLocal.getConfiguration();
    Layout<String> layout = PatternLayout.newBuilder().withPattern(prefix + " %c %m
").withConfiguration(config)
        .build();
    Appender appender = ConsoleAppender.createDefaultAppenderForLayout(layout);
    appender.start();
    config.addAppender(appender);
    AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
    AppenderRef[] refs = new AppenderRef[] { ref };
    LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.ALL, getClass().getName(), "true", refs, null,
        config, null);
    loggerConfig.addAppender(appender, null, null);
    config.addLogger(LOGGER_NAME, loggerConfig);
    ctxLocal.updateLoggers();
  }

  void initLoggerConfig(String prefix) {
    ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    builder.setStatusLevel(Level.ERROR);
    builder.setConfigurationName("BuilderTest");
    builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.NEUTRAL).addAttribute("level",
        Level.DEBUG));
    AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").addAttribute("target",
        ConsoleAppender.Target.SYSTEM_OUT);
    appenderBuilder.add(builder.newLayout("PatternLayout").addAttribute("pattern", prefix + " %c %m
"));
    appenderBuilder.add(
        builder.newFilter("MarkerFilter", Filter.Result.DENY, Filter.Result.NEUTRAL).addAttribute("marker", "FLOW"));
    builder.add(appenderBuilder);
    builder.add(builder.newLogger(LOGGER_NAME, Level.ALL).add(builder.newAppenderRef("Stdout"))
        .addAttribute("additivity", false));
    builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef("Stdout")));
    ctx = Configurator.initialize(builder.build());
  }
}

public class TestMain {
  static Lambda lamb = new Lambda();
  private static Logger logger = LogManager.getLogger();

  public static void main(String[] args) {
    Configurator.setLevel(logger.getName(), Level.ALL);
    List<String> a = Arrays.asList("ONE ", "TWO ", "THR ");
    for (String i : a) {
      lamb.handle(i);
    }

  }
}

以上是关于在运行时更新log4j2模式的主要内容,如果未能解决你的问题,请参考以下文章

更新片段参数的最佳实践?

如何在 IDE 中使用一个 log4j2 配置文件进行运行时,使用另一个 log4j2 配置文件进行打包/部署?

可以更新片段而不是创建新实例吗?

如何以编程方式在运行时添加 Log4J2 附加程序?

log4j2:运行时重新配置记录器的问题

滑动时 ViewPager 更新片段