Log4j – Configuring Appenders Programatically

Step 1) Create maven project. Follow the steps given in this post to create Maven Project

Step 2) Get Log4j by adding below dependency in pom.xml and build the project

Step 3) Add AppendersByProgram.java class

  • Get the root logger by calling getRootLogger() method of Logger class
  • Create a Layout object based on your requirement
  • Add Appender object of your choice into RootLogger object like below

or

Based on your Appender configuration all the log will get printed . Suppose if you have configured ConsoleAppender then all the logs will get printed on Console. Where to incase of RollingFileAppender all the log will get diverted to the mentioned log file.

Step 5) Execute your program

Right, click and run as a java program. You should get below output

Leave a Reply

Your email address will not be published. Required fields are marked *