'Dynamically adding and removing appender in log4j 2

We are migrating from Log4J 1.X to Log4J 2.17.1. Our application requires dynamic creation of log files for a transaction. Once the transaction is complete the log files need to be closed. I could figure out how to add an appender and logger and initialize the Configuration. But not sure how to create and remove appenders after configuration is initialized.

Here is my code-

    ConfigurationBuilder<BuiltConfiguration> builder
    = ConfigurationBuilderFactory.newConfigurationBuilder();

    AppenderComponentBuilder console 
    = builder.newAppender("stdout", "Console"); 

    AppenderComponentBuilder file1 
    = builder.newAppender("log1", "File"); 
    file1.addAttribute("fileName", "logging1.log");         


    LayoutComponentBuilder standard 
    = builder.newLayout("PatternLayout");
    standard.addAttribute("pattern", "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n");

    console.add(standard);

    file1.add(standard);
    builder.add(file1);
    builder.add(console); 

    RootLoggerComponentBuilder rootLogger 
    = builder.newRootLogger(Level.ERROR);
    rootLogger.add(builder.newAppenderRef("stdout"));

    rootLogger.add(builder.newAppenderRef("log1"));
    builder.add(rootLogger);


    LoggerComponentBuilder logger1 = builder.newLogger("com1", Level.DEBUG);
    logger1.add(builder.newAppenderRef("log1"));  

    logger1.addAttribute("additivity", false);

    builder.add(logger1);

    Configurator.initialize(builder.build());

Appreciate your help.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source