Skip to content


In this lab you'll add logging to your code and see where the logging configuration goes. We'll be using the Logback logger, with the SLF4J "simple logging facade".

Step 1: Add Logback Dependency

Add the following line to your build.gradle file, inside of the dependencies block, which will tell Gradle to download the logging library dependencies.

compile 'ch.qos.logback:logback-classic:1.2.3'

You can also remove the guava dependency, as we're not using it. The resulting dependencies block should now look something like this:

dependencies {
    // logback logger, which includes the slf4j dependency
    compile 'ch.qos.logback:logback-classic:1.2.3'

    // Use JUnit test framework
    testCompile 'junit:junit:4.12'

Step 2: Make Sure IDEA Imports Changes

After you make the change to the build.gradle file, IDEA will automatically download and pull in the logger dependencies. If it doesn't do that, you will want to turn on "auto-import":

  • Open up the Gradle tool window on the right side of IDEA

  • Click on the Gradle Settings icon

  • In the dialog that pops up, make sure the **Use auto-import* checkbox is on.

Step 3: Create a Logger Instance

Now we can add an import for the logger class and instantiate one. Let's put some logging in your QuantityItem class:

  • Open up the file

  • Import the logger class and the factory using:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
  • Instantiate one that can be used throughout the class -- note that the parameter that you pass in is the containing class, so to create one for use inside the QuantityItem class, you would do:
private static final Logger LOGGER = LoggerFactory.getLogger(QuantityItem.class);

Step 4: Log Output

  • From inside the price() method (in QuantityItem), log some information about the quantity:"Price with quantity {}", quantity);
* Run your tests and look at the output

Step 5: Log an Exception

  • Instantiate a LOGGER in the class
private static final Logger LOGGER = LoggerFactory.getLogger(FileApp.class);
  • Add a logging statement in the catch portion of the try..catch block. E.g.:
    } catch (IOException e) {
  • And force that exception to occur by changing this line of code:
URL file = FileApp.class.getResource(fileName);


URL file = FileApp.class.getResource("");

Step 6: Run and See Logging

Run the FileApp application and see what output you get.

Logging Best Practices

This resource might be useful in understanding how, when, and what to log:, especially the message levels section.

A good mini-tutorial is here: