Table of Contents
Log4j is fast , reliable logging framework and can be easily integrated with the code. It is possible to enable logging at run time without using
There are two ways, you can do logging using log4j.
- log4j.properties
- log4j.xml
In this post, we will see how to configure using log4.properties
1) Create simple maven java project.
2)Â Put log4j entry in pom.xml .
1 2 3 4 5 6 7 |
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> |
3)Â Update maven project to download require jar
Right click on project-> Maven -> update project
4) Create log4j.properties file
Log to console:
1 2 3 4 5 6 7 |
log4j.rootLogger=DEBUG, console log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=[%t] %-5p %c %x - %m%n |
1 2 3 4 5 6 7 8 |
log4j.rootLogger=DEBUG, console log4j.rootLogger=DEBUG,file log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=[%t] %-5p %c %x - %m%n log4j.appender.file.File=applicationLogs.log |
If you want to log on both to console and file, you can use below code:
1 2 3 4 5 6 7 8 9 10 11 12 |
log4j.rootLogger=DEBUG, console, file log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=[%t] %-5p %c %x - %m%n log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=[%t] %-5p %c %x - %m%n log4j.appender.file.File=applicationLogs.log |
5) Sample class for Logger
Create a class called “LoggingMain.java” in src/main/java in package org.arpit.java2blog
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package org.arpit.java2blog; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; public class LoggingMain { private static final Logger logger = LogManager.getLogger(LoggingMain.class); public static void main(String[] args) { PropertyConfigurator.configure("log4j.properties"); logger.info("Hello world"); logger.info("we are in logger info mode"); } } |
6)Â Run program:
When you run above program , you will get below output to console and file(applicationLogs.log)
1 2 3 4 |
0 [main] INFO org.arpit.java2blog.LoggingMain - Hello world 1 [main] INFO org.arpit.java2blog.LoggingMain - we are in logger info mode |
Bingo!! we have successfully configured log4j using properties file in maven project.