在运行时更新log4j2模式

时间:2018-08-24 22:36:05

标签: java logging log4j log4j2

我已经花了很长时间搜索,因此在将其标记为重复项之前,请先阅读。

我有一个用参数Lambda.handle()调用的函数(id)。我想将该ID作为前缀添加到每个日志消息中。每次调用函数时都会更改。因此,我想更新记录器模式以将此ID添加为前缀。

我读过:

  • how to configure
  • how to reconfigure
  • SO和log4j论坛上的许多帖子都在谈论如何在运行时更改配置。它们要么已过时,要么根本无法正常工作。

以下代码基于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\n").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\n"));
    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);
    }

  }
}

1 个答案:

答案 0 :(得分:1)

使用D.B建议的查找方法,这就是我的解决方法。

在您的PatternLayout中添加对“变量”的引用,在以下情况下,我将其命名为MyVarialbe(您需要对%X {}使用确切的语法:

appenderBuilder.add(builder.newLayout(“ PatternLayout”)                 .addAttribute(“ pattern”,“ %X {MyVariable} %msg%n%throwable”)));

稍后在代码中,您可以随时通过以下操作为其设置值:

org.apache.logging.log4j.ThreadContext.put(“ MyVariable”,extraInfo);

以编程方式使用log4j2很复杂。由于我遇到了同样的困难,并且这篇帖子已经发表了3个月,所以希望这个答案对其他人有所帮助。