Nicolas SEROT
Nicolas SEROT

Reputation: 13

How to write a specific logger in a file with Log4J 2.X ? (progammaticaly in JAVA)

I'm upgrading a code from Log4j 1.X to Log4J 2.X.

I'd like to write a specific logger in a file using Log4j 2.X. I tried some code found on Log4j website but I can't seem to find any code that does the same.

Log4j 1.X code :

    Logger LOCAL_LOGGER = Logger.getLogger(MyClass.class.getName());
    
    PatternLayout layout = new PatternLayout("mylayoutpattern");
    String logFile = "myFile";
    
    FileAppender app = new FileAppender(layout, logFile, true);
    
    LOCAL_LOGGER.addAppender(app);
    LOCAL_LOGGER.setLevel(Level.ERROR);

Upvotes: 1

Views: 921

Answers (1)

Piotr P. Karwasz
Piotr P. Karwasz

Reputation: 16045

In Log4j 2.x two main changes were introduced that concern your code:

  • the library was split into an API part and a standard implementation part. The API interface org.apache.logging.log4j.Logger that is returned from calls to LogManager.getLogger is not concerned with layout and appenders. However if you are sure the underlying implementation is Log4j2 Core, you can cast it to org.apache.logging.log4j.core.Logger (in the following code this is Logger) and proceed as you used to.
  • the components can not be built directly, but you need to use the builder pattern that was introduced in Log4j 2.x.

This sums up to the following code:

Logger logger = (Logger) LogManager.getLogger(MyClass.class.getName());
final PatternLayout layout = PatternLayout.newBuilder()//
                                          .withPattern("mylayoutpattern")
                                          .build();
final FileAppender appender = FileAppender.newBuilder()//
                                          .setLayout(layout)
                                          .withFileName("myFile")
                                          .withAppend(true)
                                          .build();
logger.addAppender(appender);
logger.setLevel(Level.ERROR);

Upvotes: 1

Related Questions