Log4j Basic Configurator Example

In this tutorials we are going to see how to create simple log4j application using Basic Configurator with java program. Add Log4j jar in your class path or Log4j maven dependency in your pom.xml . This tutorial created based on log4j 1.2.17 version. Check our latest tutorials to know about Log4j 2 .

Log4j Maven dependency

<!-- https://mvnrepository.com/artifact/log4j/log4j -->


package com.ehowtonow.log4j.basic;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

public class Log4jExample {
 private static final Logger log = Logger.getLogger(Log4jExample.class);
 public static void main(String args[]){
  log.debug("Debug message by eHowToNow");
  log.info("Info message by eHowToNow");
  log.warn("Warn message by eHowToNow");
  log.error("Error message by eHowToNow");
  log.fatal("Fatal message by eHowToNow");


Create instance for Logger class , getLogger(Log4jExample.class) method accept fully qualified class name as its argument.

In this example BasicConfigurator.configure() used to initialize log4j using java class,you can also initialize log4j by propert file or xml file.Basic configurator takes console appender as default appender and SimpleLayout as default Layout

info,debug,warn,error,fatal are the levels available in log4j. we will see about log level in upcoming chapter

Now you can run the application, you will see the following output in console.

0 [main] DEBUG com.ehowtonow.log4j.basic.Log4jExample – Debug message by eHowToNow
16 [main] INFO com.ehowtonow.log4j.basic.Log4jExample – Info message by eHowToNow
16 [main] WARN com.ehowtonow.log4j.basic.Log4jExample – Warn message by eHowToNow
16 [main] ERROR com.ehowtonow.log4j.basic.Log4jExample – Error message by eHowToNow
16 [main] FATAL com.ehowtonow.log4j.basic.Log4jExample – Fatal message by eHowToNow

Posts You may Like

  1. How to get file size using Java
  2. How to retrieve drive/root directories from system using Java
  3. Java Best Practice Naming Conventions
  4. How to delete directory using Java
  5. Java 8 Stream Filter and Collect Example
  6. How to Modify XML file using DOM Parser
  7. How to format the String by using Locale
  8. Java 7 Try statement with multi catch
  9. How to Read File using BufferedReader
  10. Java Best Practice – Indentation
  11. How to convert Array into List in Java
  12. How to Create Pretty Print JSON using Jackson
  13. Java 8 Stream has already been operated upon or closed
  14. How to find the size of directory using FileUtils
  15. Java 7 Switch statement on String

Be the first to comment

Leave a Reply

Your email address will not be published.