#
LOG4J : Configuration for Java
This tutorial explains to you how to configure the LOG4J for Java. This tutorial is using Eclipse and Maven. This is for a simple Java application.
Log4j is a Java library that is used for logging. Here is the architecture overview of log4j
framework:
Here are some good things to know regarding the log4j architecture:
- The
log4j Logger
object is responsible for capturing logging information - Each Logger is independently configurable
- A Logger can send log messages to multiple Appenders
- The
log4j Layout
object is used to format logging information (we can get "one-line-at-a-time", XML, HTML, JSON and other formats) - The
log4j Appender
object is responsible for writing (publishing) logging information to various destinations such as a files, databases, JMS, console, UNIX Syslog, etc. - The
log4j Filters
can be defined on configuration files to give more fine-grained control over the logging information (burst filters, time filters for instance). The BurstFilter is a logging filter that regulates logging traffic. - The
log4j ObjectRenderer
is provides a String representation of different objects passed to the logging framework. This object is used by log4j Layout objects. - The
log4j LogManager
read the initialization parameters and manage the log4j framework
Here are the steps for configuring an existing Maven Java application for using log4j:
- Add the following in pom.xml :
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
Build the project using Maven in order to obtain the oc4j libraries.
Create a directory "resource" (for instance) under src folder
Create the
log4j.properties
file in it.
Here is the log4j.properties content:
# Root logger option
log4j.rootLogger=INFO, stdout, file
# Log the messages to the console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Log the messages to a log file with file rolling
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\JAVA\\log4j-application.log
log4j.appender.file.MaxFileSize=4MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
When you run your project, configure the CLASSPATH and add the location of the log4j.properties files by clicking on:
Run As -> Run Configuration -> Classpath tab -> click on User Entries -> Advanced -> select Add Folder -> select the location of your log4j.properties file and then -> OK -> Run.
Now you can use log4j using a basic configuration. If you want you can extend the functionalities of log4j.