Création d'une configuration log4j2 en Java sans XML

package fr.ronanlefichant.log4jexample;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory;
import org.apache.logging.log4j.core.config.builder.api.LayoutComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.LoggerComponentBuilder;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;

public class App {

  public static void main(String[] args) {

    // Console pour écrire logger dans la console avec system.out.println
    ConfigurationBuilder < BuiltConfiguration > builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    AppenderComponentBuilder console = builder.newAppender("stdout", "Console");

    // Pattern Horodatage [nom_du_thread] NIVEAU nom_de_classe: message
    LayoutComponentBuilder pattern = builder.newLayout("PatternLayout");
    pattern.addAttribute("pattern", "%d [%t] %level %C: %msg%n%throwable");

    // Ou RootLoggerComponentBuilder pour <Root>
    LoggerComponentBuilder loggerComponentBuilder = builder.newLogger("fr.ronanlefichant.log4jexample", Level.INFO);
    loggerComponentBuilder.add(builder.newAppenderRef("stdout"));
    loggerComponentBuilder.addAttribute("additivity", false);

    console.add(pattern);
    builder.add(console);
    builder.add(loggerComponentBuilder);

    Configurator.initialize(builder.build());

    Logger LOGGER = LogManager.getLogger();

    LOGGER.info("Test");
  }

}

Commentaires