alevi.dcosta
alevi.dcosta

Reputation: 353

How to programmatically add a new logger and appender to existing XML configuration

I am using log4j2 v2.11. I have a simple log4j2.xml file. I need to perform default logging with the loggers loaded from this file. However, depending upon the process spawned, i need to create a different log file with the name of the process along with the xml loaded configuration.

I am aware of :-

    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();

    Appender appender = FileAppender.createAppender(...);
    appender.start();
    config.addAppender(appender);
    AppenderRef ref = AppenderRef.createAppenderRef(...);
    AppenderRef[] refs = new AppenderRef[] {ref};
    LoggerConfig loggerConfig = LoggerConfig.createLogger(...);
    loggerConfig.addAppender(appender, Level.DEBUG, null);
    config.addLogger("myapp.namespace", loggerConfig);
    ctx.updateLoggers();

However, createAppender and createLogger are deprecated methods in V2.11.

Besides, I am also aware of ConfigurationBuilder. I have tried it out and it seems it is for programmatically building the Configuration. I need to have the default configuration to come form log4j2.xml file. And append the new appender (with new file name and logger).

Upvotes: 3

Views: 996

Answers (2)

alevi.dcosta
alevi.dcosta

Reputation: 353

Thanks Vikas. Sorry for the late response. Before i received your response i resolved my issue in a different way. As you might have guessed i needed to specify the name of the log file at runtime.

I used the fileName="${sys:logpath.name}" configuration and set its value System.setProperty("logpath.name","logs/.log");

Upvotes: 0

Vikas Sachdeva
Vikas Sachdeva

Reputation: 5813

In the new version of log4j2, Appender instance can be created by using its Builder. So, for creating FileAppender instance, you can write something like below -

Appender fileAppender = FileAppender.newBuilder().setName("fileAppender")
                .withFileName(basePath + "dynamic_logs.log").setLayout(PatternLayout.SIMPLE_CONVERSION_PATTERN)
                .build();

And for creating logger, LoggerConfig class static methods are used. There are 2 methods for creating logger in LoggerConfig class. Only one method that accepts first argument additivity as String value has been deprecated. Another method that accepts first argument as boolean type is used now.

One way of creating dynamic Logger is mentioned below -

LoggerConfig dynamicLogger = LoggerConfig.createLogger(false, Level.INFO, "logger.name", null, refs, null, config, null);

Upvotes: 3

Related Questions