The Geek Biker

Rambles of a geek that rides a bike

Monthly Archives: October 2015

Add logging to a Java application

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/

Step 1: Create a new application

Start up Netbeans and select to create a new project. We want to create a Maven project.

After selecting a Java Maven project, name your project. I called mine MyFirstLoggingApplication.

Step 2: 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.

Step 3: Add Log4J logging module and configure

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:

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

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

Step 4: 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..."); 
 }
}

Step 5: 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!

Simple JAVA Scheduler

As added on instructables

I’ve been tinkering with code again and wanted a simple way to schedule a few jobs on my PC. So got dusted off the old JAVA IDE and saw what was out there.

Required:

  • JAVA 7
  • Netbeans
  • Maven

I know the basics of the above three, so this will be a ‘dummies’ guide.

You can download all of the above in one single package here:

https://netbeans.org/downloads/

Step 1: Start Netbeans and create a project

  1. Start Netbeans and create a new Maven project (Image 1). I chose Maven as I found it the easiest way to add some of the required libraries for logging and scheduling.
  2. Next, add a project name. I chose MyFirstScheduler. (Image 2)

Step 2: What is in a clean project?

A clean maven project only contains a single file. The POM file is basically the foundation that holds the key to how the project is built, what it should include, and way more. (Image 1)

We will add a main class to make this project a bare bone run-able project.

  1. Right click on the source package and select to create a new Java Class.(Image 2)
  2. Name the new class
  3. Add the good old MAIN method to make it executable
public static void main(String[] args) {
	System.out.println("My First Scheduler!"); // Display the string.
}

4. Execute the application by selecting Run (F6) and you should see

<p>cd C:\Users\Tertius\Documents\NetBeansProjects\MyFirstScheduler; "JAVA_HOME=C:\\Program Files\\Java\\jdk1.8.0_40" cmd /c "\"\"C:\\Program Files\\NetBeans 8.0.2\\java\\maven\\bin\\mvn.bat\" -Dexec.args=\"-classpath %classpath com.thegeekbiker.myfirstscheduler.TheSchedulerApp\" -Dexec.executable=\"C:\\Program Files\\Java\\jdk1.8.0_40\\bin\\java.exe\" -Dmaven.ext.class.path=\"C:\\Program Files\\NetBeans 8.0.2\\java\\maven-nblib\\netbeans-eventspy.jar\" -Dfile.encoding=UTF-8 org.codehaus.mojo:exec-maven-plugin:1.2.1:exec\""<br>Running NetBeans Compile On Save execution. Phase execution is skipped and output directories of dependency projects (with Compile on Save turned on) will be used instead of their jar artifacts.
Scanning for projects...
                                                                        
------------------------------------------------------------------------
Building MyFirstScheduler 1.0-SNAPSHOT
------------------------------------------------------------------------</p><p>--- exec-maven-plugin:1.2.1:exec (default-cli) @ MyFirstScheduler ---
My First Scheduler!
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 1.068s
Finished at: Fri Oct 30 21:53:19 AWST 2015
Final Memory: 4M/119M
------------------------------------------------------------------------</p>

Notice the line ‘My First Scheduler!’

In the next steps we’ll add the first dependency/library to use in the project.

Step 3: Add Cron4J scheduling package

From the Cron4J homepage:

cron4j is a scheduler for the Java platform which is very similar to the UNIX cron daemon. With cron4j you can launch, from within your Java applications, any task you need at the right time, according to some simple rules.

So first we open the pom.xml file in netbeans and add the following:

<dependencies>
  <dependency>
    <groupId>it.sauronsoftware.cron4j</groupId>
    <artifactId>cron4j</artifactId>
    <version>2.2.5</version>
  </dependency>
</dependencies>

or just copy and paste from the Maven Repository.

Netbeans should download the required java packages and you should end up with something like what is in the image.

Step 4: Adding a scheduler

We should now be in a position to add our fist scheduled. Cron4J can execute a number of jobs.

We will start out with something simple and nonsensical. I’ll expand on one of the examples from the cron4j website. We are going to start notepad.exe Monday, Tuesday, Wednesday, Thursday and Friday at 11:59.

Cron4J uses patterns to let it know when to start a job. The above’s pattern would be:

59 11 * * 1,2,3,4,5 notepad.exe

But we need to add the scheduler first. To do that, you need to add the following code to your main class:

package com.thegeekbiker.myfirstscheduler;

import it.sauronsoftware.cron4j.ProcessTask;
import it.sauronsoftware.cron4j.Scheduler;
public class TheSchedulerApp {
    public static void main(String[] args) {
	System.out.println("My First Scheduler!"); // Display the string.
	//Add a schedule to run
        Scheduler myFirstSchedule = new Scheduler();
        //The task is the application you want to start
        ProcessTask task = new ProcessTask("C:\\Windows\\System32\\notepad.exe");
        //The schedule pattern is when we want to execute the task.
        myFirstSchedule.schedule("59 11 * * 1,2,3,4,5", task);
	//start the schedule
	myFirstSchedule.start();
    }
}

See the image below.

Step 5: Running the application

You can now run the application through Netbeans. When you hit the time and day, boom! , notepad opens.

Note how I’ve added another output string to show that the scheduler started.

In following instructables I’ll show how to expand on this to do the following:

  • Add logging so you know what is happening in your application
  • Add you own code to execute in a schedule
  • Package an application up to run outside of Netbeans.