Add Logging to a Java Application

by TvZ in Circuits > Software

6095 Views, 10 Favorites, 0 Comments

Add Logging to a Java Application

log4j2-poweredby-logo-w3000.jpg

Logging in any application can be quite useful as it lets you know what happened to a certain point in time. I'll try to explain a simple way to add logging to a Java application in as little as possible steps.

If you are reading past the first bit I can only assume you need logging in your application and I don't have to go into detail about why it is so widely used but rather into getting it added.

Required:

  • Java 7 (The engine that makes stuff run)
  • Netbeans (The application we put our code in)
  • Maven (The useful tool to get more useful tools for our application)

All downloadable in a single package at https://netbeans.org/downloads/

Create a New Application

step1_new_application.png
step1_name_application.png

  1. Start up Netbeans and select to create a new project. We want to create a Maven project.
  2. After selecting a Java Maven project, name your project. I called mine MyFirstLoggingApplication.

Add a Main Class - Make It Executable

You should now have a brand new clean application. We first need to create a simple Java class and add the main method to make it executable. We will keep it simple and add a few buts to write something to the console.

  • Create a new java class
  • Name it. My example is MyLoggingApplication
  • Next we add the main method with this code:


/*
* My application header
*/
package com.thegeekbiker.myfirstloggingapplication;
/**
* @author LordFluffyGoggles
*/
public class MyLoggingApp {
//main method
public static void main(String[] args) {
System.out.println("Application starting processes here."); // Display the string.
System.out.println("Application do more stuff here.");
System.out.println("Application end processes here.");
}
}

When you run this application you will see three lines write to the output. The first represents the starting processes, the main application doing things and the last is the application finishing off.

Add Log4J Logging Module and Configure

step3_new_other_other.png
step3_properties_file.png
step3_properties_naming.png

We will be using the Log4J module. From there site:

Inserting log statements into code is a low-tech method for debugging it. It may also be the only way because debuggers are not always available or applicable. This is usually the case for multithreaded applications and distributed applications at large.

Open the pom.xml file. This file is how Maven downloads required packages and modules for us to use.

Add the following code:

</dependencies>
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies>

If you start the application now you will see that the application complains that there is no configuration available for log4j so the logging is not enabled.

There are various ways to configure log4j. We will use a properties file.

Create a file called log4j.properties in the root folder of the application. This is not the ideal spot for it, but in a later post I'll write about moving resource files.

Now we want our application to still write all the logging to the console, but we will expand on it to write to a log file as well. Just in case you need to investigate an issue at a later time.
Add the following section to your log4j.properties file:

# Root logger option
log4j.rootLogger=DEBUG, 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
# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\logs\\MyLoggingApp.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

Add Logging to the Application

We need to know which class through an error in our application. So we need to associated a logger instance with the class that writes to the log files. For our test application it is pretty straight forward as we just have one class.

Add the following line to the class:

final static Logger logger = Logger.getLogger(MyLoggingApp.class);

Now we need to configure log4j to read the properties file we created. Luckily this is only required once and not for each class.
The following code in the main method should be enough to load up the properties file:

PropertyConfigurator.configure("log4j.properties");  

If you run your application now and it still complains about not finding the file, then you might need to copy the file to the same directory as the pom.xml file. As stated earlier, in a later post I'll talk about how to specify exactly where these types of files go

You can log at various levels in your application. Error, Warning, Debug, Info etc.

I'll add a few info and a debug here and there so you can get the idea of how and where to use it.

public class MyLoggingApp { 
final static Logger logger = Logger.getLogger(MyLoggingApp.class);

//main method
public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties");
if(logger.isInfoEnabled()) logger.info("Application starting...");
System.out.println("Application starting processes here.");
if(logger.isInfoEnabled()) logger.info("Application started successfully");
try{
System.out.println("Application do more stuff here.");
if(logger.isDebugEnabled()) logger.debug(("Application did something"));
} catch (Exception e){
logger.error("Something went wrong :"+e);
}
if(logger.isInfoEnabled()) logger.info("Application finishing up...");
System.out.println("Application end processes here.");
if(logger.isInfoEnabled()) logger.info("Application finished...");
}
}

Run the Application

All that is left is to run the application and inspect the log file.

2015-10-31 22:00:30 INFO MyLoggingApp:18 - Application starting...
2015-10-31 22:00:30 INFO MyLoggingApp:20 - Application started successfully
2015-10-31 22:00:30 DEBUG MyLoggingApp:23 - Application did something
2015-10-31 22:00:30 INFO MyLoggingApp:27 - Application finishing up...
2015-10-31 22:00:30 INFO MyLoggingApp:29 - Application finished...

Since nothing went wrong in our application, the ERROR line didn't show.

Done!