Wednesday, December 4, 2013

How To Use Apache Log4j In Your Java Application

Hi guys, being able to log what your applications behave since its first released or under development is one of the great things you need to consider being a Developer. So in this tutorial, I'm going to show you the basic on how to install Apache Log4j to your own java application.

First, download the library and create a new project in Eclipse then add the log4j to your classpath.
Make a new class by right clicking the src folder and select New > Class and name your class an appropriate name.

In log4j, there are a lot of levels, namely:

  1. DEBUG
  2. ERROR
  3. FATAL
  4. INFO
  5. TRACE
  6. WARN
Now copy and paste this code:

import org.apache.log4j.Logger;
public class MyLogger{
   private static Logger log = Logger.getLogger(LogClass.class);
   public static void main(String[] args) {
      log.trace("Trace Message..");
      log.debug("Debug Message..");
      log.info("Info Message..");
      log.warn("Warn Message..");
      log.error("Error Message..");
      log.fatal("Fatal Message..");
   }
}
Output:
Debug Message..
Info Message..
Warn Message..
Error Message..
Fatal Message..
Depending on how crucial the application is executing you will use the right level for your application.
Say for example, your application is trying to write to a file but it there's not enough permission, you can then log it and be like:
ERROR: Unable to write to a file: 'C:\updates.json'
That's it! I hope you learned something new about this wonderful library! Thanks for reading guys. If you have questions then feel free to contact me or post your problems here regarding this library.

No comments:

Post a Comment