log4j properties example
This is an example of how to configure log4j
, using the log4j.properties
file. Log4j
is a logging library for Java, licensed under the Apache Software Foundation. It is a Logging Framework that is thread-safe and flexible, thanks to its configuration. With log4j
you can configure logging in runtime, and you can log to different outputs, such as files or even databases.
Basically, it consists of loggers
to log the messages, appenders
to publish the messages to different outputs and layouts
to format the log messages. All these components are configured in the log4j.properties
file, which is placed in the application classpath.
Below, we have created an example with a class that uses a logger to log messages to a file and to the console.
You may skip project creation and jump directly to the beginning of the example below.
Our preferred development environment is Eclipse. We are using Eclipse Juno (4.2) version, along with Maven Integration plugin version 3.1.0. You can download Eclipse from here and Maven Plugin for Eclipse from here. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using the JDK 7_u_21.
Let’s begin,
1. Create a new Maven project
Go to File -> Project ->Maven -> Maven Project.
In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option is checked, hit “Next” to continue with default values.
In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. We will set the “Group Id” variable to "com.javacodegeeks.snippets.enterprise"
and the “Artifact Id” variable to "log4jexample"
. The aforementioned selections compose the main project package as "com.javacodegeeks.snippets.enterprise.log4jexample "
and the project name as "log4jexample"
. Hit “Finish” to exit the wizard and to create your project.
The Maven project structure is shown below:
- It consists of the following folders:
- /src/main/java folder, that contains source files for the dynamic content of the application,
- /src/test/java folder contains all source files for unit tests,
- /src/main/resources folder contains configurations files,
- /target folder contains the compiled and packaged deliverables,
- the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.
2. Add log4j dependency
Add the log4j dependency in Maven’s pom.xml
file, by editing it at the “Pom.xml” page of the POM editor, as shown below:
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javacodegeeks.snippets.enterprise</groupId> <artifactId>log4jexample</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> </project>
As you can see Maven manages library dependencies declaratively. A local repository is created (by default under {user_home}/.m2 folder) and all required libraries are downloaded and placed there from public repositories. Furthermore intra – library dependencies are automatically resolved and manipulated.
3. Create the log4j.properties file
The log4j.properties
file is placed under the resources
folder of the project. This is where all logging components are configured. First, the rootLogger
is where the logging level and the appender that will be used are set. The logging levels are (from smaller to greater) : ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF
. When a logging level is set, only messages belonging to this level or greater levels are printed.
Here, we use two appenders, one appender to log to a file and another one to log to the console. The first appender uses the org.apache.log4j.FileAppender
and the second one the org.apache.log4j.ConsoleAppender
. The first appender has a file
attribute, where the logging file is set, whereas the second one has a target
attribute which is set to System.out
. Both appenders use a layout for their log files. The org.apache.log4j.PatternLayout
is used and the ConversionPattern
is set to %d{dd/MMM/yyyy HH:mm:ss,SSS}- %c{1}: %m%n
:
%d{dd/MMM/yyyy HH:mm:ss,SSS}
is used to set the date pattern, %c{1}
is used to print the class name, %m
to print the message, and %n
to leave an empty line.
log4j.properties
log4j.rootLogger = INFO, File, stdout log4j.appender.File=org.apache.log4j.FileAppender log4j.appender.File.File=C:\\logs\\logs.log log4j.appender.File.layout=org.apache.log4j.PatternLayout log4j.appender.File.layout.conversionPattern=%d{dd/MMM/yyyy HH:mm:ss,SSS}- %c{1}: %m%n 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{dd/MMM/yyyy HH:mm:ss,SSS}- %c{1}: %m%n
4. Create an Example class
Example.java
class uses a org.apache.log4j.Logger
to log messages both to a file and to the console. The logger is stated as a static
field, initialized by the getLogger(String name)
API method of org.apache.log4j.Logger
, making use of the classe’s name. Example.java
class has a main method, where the user is asked to type number between 0 and 100. The logger first logs an info message, using info(Object message)
API method of org.apache.log4j.Logger
. If the number is greater than 100, an exception is thrown and the logger logs an error message, making use of error( Object message)
API method of org.apache.log4j.Logger
. If the number is lower than 100, then the logger logs a debug message, with debug(Object message)
API method of org.apache.log4j.Logger
.
Example.java:
package com.javacodegeeks.snippets.enterprise.log4jexample; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.log4j.Logger; public class Example { static Logger log = Logger.getLogger(Example.class.getName()); public static void main(String[] args) throws IOException{ System.out.println("====> Please insert a number from 0 to 100 : \n====> "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int number = Integer.valueOf(br.readLine()); log.info("You inserted the number:"+number); if(number > 100) { log.error("You entered a wrong number!"); throw new IOException(); } else { log.debug("Number is smaller than 100, so it is correct!"); } } }
5. Run the application
Run the application, typing a number greater than 100. The result in the console will be the one below:
====> Please insert a number from 0 to 100 :
====>
456
25/Sep/2014 01:17:58,176- Example: You inserted the number:456
Exception in thread "main" 25/Sep/2014 01:17:58,178- Example: You entered a wrong number!
java.io.IOException
at com.javacodegeeks.snippets.enterprise.log4jexample.Example.main(Example.java:20)
And the log file is the one below:
logs.log:
25/Sep/2014 01:17:58,176- Example: You inserted the number:456 25/Sep/2014 01:17:58,178- Example: You entered a wrong number!
As you can see, since the log level is set to INFO
, only info and error messages are printed. You can change the logging level to DEBUG
and ERROR
and see what happens. Then you can try the same steps, typing a correct number to see what happens.
6. Download the Eclipse Project
This was an example of how to configure log4j with log4j.properties
file.
You can download the full source code of this example here: log4jPropertiesExample