Simple log4j configuration in java

Introduction

The purpose of inserting log statements into the code is a low-tech method for debugging it. It may also be the only way because debuggers are not always available or applicable. This is often the case for distributed applications.
Features of Log4j

We can enable logging at runtime without modifying the application binary.

We can control the behavior of logging by editing only the configuration file, no need to touch the application binary.

Developer are always clear with detailed context for application failures.

Log4j has one of the distinctive features – the notion of inheritance. Using this logger hierarchy feature we are able to control the log statements output at arbitrarily fine granularity but also at great ease. This helps to reduce the volume of logged output and the cost of logging.

We can set many targets for the log output such as a file, an OutputStream, a java.io.Writer, a remote log4j server, a remote Unix Syslog daemon, or many other output targets.

Loggin Levels

FATAL: shows messages at a FATAL level only
ERROR: Shows messages classified as ERROR and FATAL
WARNING: Shows messages classified as WARNING, ERROR, and FATAL
INFO: Shows messages classified as INFO, WARNING, ERROR, and FATAL
DEBUG: Shows messages classified as DEBUG, INFO, WARNING, ERROR, and FATAL
ALL – The ALL Level has the lowest possible rank and is intended to turn on all logging.
OFF – The OFF Level has the highest possible rank and is intended to turn off logging.

For more information please go through Apache Log4j

I am giving here simple logginh example using log4j.xml configuration. This will log the messages to the console as well as to file. I have used here RollingFileAppender so that we can have multiple backup files. This log4j.xml file is put into the classpath i.e. under src directory.

 

Write a simple java class for testing it. We need log4j.jar file to be put into the classpath.

 

Console output:

 

That’s all. Thanks for your time. Please do not forget to leave a comment.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.