Aga
Aga

Reputation: 33

Migration from log4j to log4j2 - FileAppender set new file name & acitvateOptions

We are migrating to log4j2. I can't find anywhere how to rewrite a part of code.

LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
Configuration config = context.getConfiguration();
RollingFileAppender fileAppender = config.getAppender("file");

(...)

fileAppender.setFile(newFileName); //this part
fileAppender.activateOptions(); //and this part

Does anyone know how it should be written correctly? Any help would be greatly appreciated and I am sorry if it is a dumb question.

EDIT: I also have a problem with my class which (with log4j v.1) implements LoggerFactory. I found here: log4j migration to log4j2 that I should use "other mechanism". I am not sure if I should use LoggerContextFactory here or something else:

class MyNameLoggerFactory implements LoggerFactory {
    (...)
    void init() {
       //sets quiet mode
       //init DOMConfigutator
       //configure using log4j config xml
    }

    Appender getFileAppender(File file) {
        //returns a FileAppender
    }

    @Override
    public MyNameLoggerFactory makeNewLoggerInstance(String name) {
        return new MyNameLoggerFactory (name);
    }
}

The XML configuration loaded here has appenders like an EmailSender, ConsoleAppender and RollingFileAppender (I will need to convert the xml too, I think). If I understood this How to specify Log4J 2.x config location? correctly, instead of DOMConfigurator I will use here (in my init method) an initialize method with null ClassLoader?

This is really an old project, written by many different people during the years, and it is a mess. Thank you for any help.

Upvotes: 1

Views: 2665

Answers (1)

lazyCoder
lazyCoder

Reputation: 11

You can try this way.

Layout<? extends Serializable> old_layout = fileAppender.getLayout();
fileAppender.stop();

//delete old appender
((org.apache.logging.log4j.core.Logger)logger).removeAppender(fileAppender);

RollingFileAppender appender = RollingFileAppender.newBuilder().withFileName(newFileName).withAppend(true).withLocking(false)
        .setName(fileAppender.getName()).setIgnoreExceptions(true).withFilePattern(newFileName.concat(".%d")).withPolicy(fileAppender.getTriggeringPolicy())
        .withStrategy(DefaultRolloverStrategy.newBuilder().withMax(String.valueOf(5)).build())
        .setLayout(old_layout).setConfiguration(config).build();
appender.start();

((org.apache.logging.log4j.core.Logger)logger).addAppender(appender);

Upvotes: 1

Related Questions