log4j Sample Program - Log4j

What is log4j Sample Program?

We make sure that we understood how to make a configuration file. This chapter defines how to generate debug messages and log them in a simple text file.

Next is a simple configuration file created for our instance? Let us revise it once again:

  • The level of the root logger is defined as DEBUG and attaches appender named FILE to it.
  • The appender FILE is defined as org.apache.log4j.FileAppenderand writes to a file named log.out located in the log directory.
  • The layout pattern defined is %m%n, which means the printed logging message will be followed by a newline character.

The contents of log4j.properties file are as follows –

Using log4j in Java Program

The resulting Java class is a very simple example that initializes, and then uses, the log4j logging library for Java applications.

Compile and Execute

Here are the steps to compile and run the above-mentioned program. Make sure you have set PATH and CLASSPATH suitably before going on for the compilation and execution.

All the libraries should be available in CLASSPATH and your log4j.properties file should be available in PATH. Follow the steps give below −
Create log4j.properties as shown above.

  • Create log4jExample.java as shown above and compile it.
  • Execute log4jExample binary to run the program.

You would get the following result inside /usr/home/log4j/log.out file –

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Log4j Topics