user15584948
user15584948

Reputation: 21

How to add Console appenders(which has pattern layout) to Root Logger programtically

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

Upvotes: 0

Views: 514

Answers (1)

Piotr P. Karwasz
Piotr P. Karwasz

Reputation: 16045

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.

Upvotes: 0

Related Questions