0

I need to add a console appender with pattern layout to Root Logger programtically.My previous code with log4j1.x has something like Logger.getLogger(new Appender(console,fname,patternlayout,"Specific pattern") How to convert this one to log4j 2.3.2

1 Answers1

0

Log4j 2.3.2 is an old version and lacks many new features like the ConfigurationBuilder API.

However you can build your console appender and attach directly to the root logger through:

      final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
      final Logger logger = ctx.getLogger(LogManager.ROOT_LOGGER_NAME);

      final Layout<String> layout = PatternLayout.newBuilder()
            .withConfiguration(ctx.getConfiguration())
            .withPattern("some pattern")
            .build();
      final Appender appender = ConsoleAppender.newBuilder()
            .setName("some name")
            .setLayout(layout)
            .build();
      /*
       * This is simpler, but it is not API:
       *
       * logger.addAppender(appender);
       * 
       * Instead we shoud use:
       */
      ctx.getConfiguration().addLoggerAppender(logger, appender);

Remark: this is a temporary patch of the current configuration. If the configuration is reloaded (e.g. the log4j2.xml file changes), the modifications will be lost.

Piotr P. Karwasz
  • 12,857
  • 3
  • 20
  • 43