This utility will help you to keep track of everything your code does (and the government will keep track of everything you do in your life, just kidding -__-). Well, I'm going to show a short but solid example on how to use log4j. In this project we are going to log everything into a text file.
For this exercise we are going to use:
- Java 1.7
- Maven
- log4j
- Eclipse IDE
First of all, let's create a Maven project in Eclipse. (if you don't know how to install Maven in your PC, please go here)
Select option "Create a simple project"
Then fill all the fields according the bellow image. Here we are putting the info needed for our pom.xml
When done with these settings, open your pom.xml file and add the next lines:
<properties> <jdk.version>1.7</jdk.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> </dependencies>
Your pom.xml should look like this:
What we just did, was add some dependencies to our project, so with the help of mighty Maven, we are going to install them. Right click on pom.xml and select "Maven install"... Maven will pull all the jars needed (to your .M2 reposotory), in this case log4j
You should get a "BUILD SUCCESS" message in your console:
Log4j needs some properties file in which we specify its configuration. Let's create a "log4j.properties" file and added to our project:
Once created, double click on it, and add the following code:
# Root logger option log4j.rootLogger=ERROR, stdout, file
log4j.rootLogger=INFO, stdout, file# Redirect log messages to 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 # Rirect log messages to a log file log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=D:\\log4j-application.log log4j.appender.file.MaxFileSize=5MB 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
Here we are specifying how and where to append the logs. Take a look at those lines and change accordingly.
Now we are going to proceed to write our code. Create a class and let's name it "HelloExample.java", here is the code:
package com.rolandoFebrero; import org.apache.log4j.Logger; public class HelloExample { final static Logger logger = Logger.getLogger(HelloExample.class); public static void main(String[] args) { HelloExample obj = new HelloExample(); obj.runMe("Log4j Example"); } private void runMe(String parameter){ if(logger.isDebugEnabled()){ logger.debug("This will be logged as DEBUG : " + parameter); } if(logger.isInfoEnabled()){ logger.info("This will be logged as INFO : " + parameter); } logger.warn("This will be logged as WARN : " + parameter); logger.error("This will be logged as ERROR : " + parameter); logger.fatal("This will be logged as FATAL: " + parameter); } }
now, create another class, this time let's name it "HelloExampleException.java". Here is the code:
package com.rolandoFebrero; import org.apache.log4j.Logger; public class HelloExampleException { final static Logger logger = Logger.getLogger(HelloExampleException.class); public static void main(String[] args) { HelloExampleException obj = new HelloExampleException(); try{ obj.divide(); }catch(ArithmeticException ex){ logger.error("Something wrong!!!, you are getting an exception ", ex); } } private void divide(){ int i = 3 / 0; } }
If you look at the code, in our first class, HelloExample.java, we are just printing a message, but with different log levels, such as debug, info, warn, error, fatal. This helps us to identify the kind of message we want to log. On the other file, HelloExampleExceptio.java, we are performing some math operation. In the main method we are making a call to "divide()". This divide() method just performs one single math operation, which is "3 / 0". Obviously, we can't divide a number by zero, so we will get an exception, in this specific case, an Arithmetic exception. I did that on purpose so we can see how an exception is logged by log4j.
Now, just right click on either HelloExample.java or HelloExampleExceptio.java; you might see the message in you console. Then go to where "log4j-application.log" file is located (hint: specified in log4j.properties) and there you'll find all the logs...
If you want to download the code for this project just go to my github account:
https://github.com/rolando-febrero/log4j-maven-Example.git
Programming thought of the day:
- If at first you don’t succeed; call it version 1.0.
No comments:
Post a Comment