medium.com 12 min read Original Source

Mastering Java Logging Frameworks with Examples — Part 1

Overview

Haven’t you experienced getting lost in how the logging work in Java? Some may feel that it just works and logs get printed.

It is simply because developers sometimes need to encapsulate some components (second-party packages) into an application, so they cannot guarantee that a specified logging tool is used for all components. In addition, the application may use a lot of third-party packages that use different logging tools. For example, if an application has two components that use different logging tools, the application will have output logs from both logging tools, resulting in complicated logging.

It is essential to understand how logging your Java application actually works especially when you need to modify the behavior of logging for an existing project.

Some of the most popular Java logging frameworks are:

  1. Java Logging API (java.util.logging, also called JUL): The Java Logging API is a built-in logging framework in the Java standard library. It provides basic logging features such as log levels, loggers, and handlers, but lacks some advanced features compared to other logging frameworks.
  2. SLF4J: SLF4J (Simple Logging Facade for Java) provides a simple facade or wrapper API over different logging frameworks, including Log4j and Logback. It provides a consistent API for developers to use and makes it easier to switch between logging frameworks.
  3. Logback: Logback is a successor to Log4j and provides similar features with improved performance and configurability. It has a pluggable architecture that allows developers to add new appenders and filters.
  4. Log4j: Log4j is a powerful and widely-used logging framework that provides high-speed logging, flexible configuration options, and support for multiple appenders and logging levels. It also has support for filtering and pattern-based layouts.
  5. Log4j2: Log4j2 is a newer version of Log4j that provides improved performance and scalability, along with features such as asynchronous logging and garbage-free logging. It also has support for custom log levels and logging contexts.

In this post, we will demonstrate the use of JUL, SLF4J and Logback with examples while Log4J and Log4J2 are detailed in the next post.

JUL

java.util.logging (JUL) is a built-in logging framework in Java that provides basic logging capabilities. It is included in the Java standard library and is available in all Java implementations. JUL provides a simple API for logging messages with different levels of severity and includes support for logging to different outputs, such as the console, a file, or a remote server.

Logging Levels

The Level class defines a set of standard logging levels that can be used to control logging output. The logging Level objects are ordered and are specified by ordered integers. Enabling logging at a given level also enables logging at all higher levels.
Clients should normally use predefined Level constants such as Level.SEVERE

The levels in descending order are:

SEVERE (highest value)
WARNING
INFO
CONFIG
FINE
FINER
FINEST (lowest value)
SEVERE (highest value)
WARNING
INFO
CONFIG
FINE
FINER
FINEST (lowest value)

In addition, there is a level OFF that can be used to turn off logging, and a level ALL that can be used to enable the logging of all messages.

Basic Logging example without explicit handler

Here’s an example of how to use java.util.logging to log messages:

import java.util.logging.*;

public class ExampleLogger {
    private static final Logger LOGGER = Logger.getLogger(ExampleLogger.class.getName());

    public static void main(String[] args) {
        LOGGER.info("Starting application...");

        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            LOGGER.log(Level.SEVERE, "An error occurred", e);
        }

        LOGGER.info("Application finished.");
    }
}
import java.util.logging.*;

public class ExampleLogger {
    private static final Logger LOGGER = Logger.getLogger(ExampleLogger.class.getName());

    public static void main(String[] args) {
        LOGGER.info("Starting application...");

        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            LOGGER.log(Level.SEVERE, "An error occurred", e);
        }

        LOGGER.info("Application finished.");
    }
}

We should be able to see the following output on the console.

Feb 19, 2023 5:13:42 AM ExampleLogger main
INFO: Starting application...
Feb 19, 2023 5:13:43 AM ExampleLogger main
SEVERE: An error occurred
java.lang.ArithmeticException: / by zero
 at ExampleLogger.main(ExampleLogger.java:10)

Feb 19, 2023 5:13:43 AM ExampleLogger main
INFO: Application finished.
Feb 19, 2023 5:13:42 AM ExampleLogger main
INFO: Starting application...
Feb 19, 2023 5:13:43 AM ExampleLogger main
SEVERE: An error occurred
java.lang.ArithmeticException: / by zero
 at ExampleLogger.main(ExampleLogger.java:10)

Feb 19, 2023 5:13:43 AM ExampleLogger main
INFO: Application finished.

In this example, we first obtain a logger instance by calling Logger.getLogger() and passing in the name of the current class. We then log an informational message using the info() method.

Next, we intentionally trigger an ArithmeticException by dividing by zero, and log the exception using the log() method with a Level.SEVERE severity level. This logs both the error message and the stack trace of the exception.

Finally, we log another informational message to indicate that the application has finished. By default, JUL logs messages to the console, but you can configure it to log to a file or a remote server by using Handler classes such as ConsoleHandler, FileHandler, and SocketHandler.

Using ConsoleHandler

import java.util.logging.*;

public class ExampleLogger {
    private static final Logger LOGGER = Logger.getLogger(ExampleLogger.class.getName());

    public static void main(String[] args) {
        // create a new console handler
        ConsoleHandler consoleHandler = new ConsoleHandler();
        // set the handler's log level to FINEST
        consoleHandler.setLevel(Level.FINEST);
        // add the handler to the logger
        LOGGER.addHandler(consoleHandler);

        LOGGER.info("Starting application...");

        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            LOGGER.log(Level.SEVERE, "An error occurred", e);
        }

        LOGGER.info("Application finished.");
    }
}
import java.util.logging.*;

public class ExampleLogger {
    private static final Logger LOGGER = Logger.getLogger(ExampleLogger.class.getName());

    public static void main(String[] args) {
        // create a new console handler
        ConsoleHandler consoleHandler = new ConsoleHandler();
        // set the handler's log level to FINEST
        consoleHandler.setLevel(Level.FINEST);
        // add the handler to the logger
        LOGGER.addHandler(consoleHandler);

        LOGGER.info("Starting application...");

        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            LOGGER.log(Level.SEVERE, "An error occurred", e);
        }

        LOGGER.info("Application finished.");
    }
}

In this example, we first create a new ConsoleHandler instance and set its log level to Level.FINEST. We then add the handler to the logger instance using the addHandler() method.

By default, ConsoleHandler logs messages with a severity level of Level.INFO and higher to the console. However, by setting the log level to Level.FINEST, we can see all log messages, including those with lower severity levels.

When we run this example, we should see log messages printed to the console, including the informational messages and the error message and stack trace.

Feb 19, 2023 5:19:47 AM ExampleLogger main
INFO: Starting application...
Feb 19, 2023 5:19:47 AM ExampleLogger main
INFO: Starting application...
Feb 19, 2023 5:19:47 AM ExampleLogger main
SEVERE: An error occurred
java.lang.ArithmeticException: / by zero
 at ExampleLogger.main(ExampleLogger.java:17)

Feb 19, 2023 5:19:47 AM ExampleLogger main
SEVERE: An error occurred
java.lang.ArithmeticException: / by zero
 at ExampleLogger.main(ExampleLogger.java:17)
Feb 19, 2023 5:19:47 AM ExampleLogger main
INFO: Application finished.
Feb 19, 2023 5:19:47 AM ExampleLogger main
INFO: Application finished.
Feb 19, 2023 5:19:47 AM ExampleLogger main
INFO: Starting application...
Feb 19, 2023 5:19:47 AM ExampleLogger main
INFO: Starting application...
Feb 19, 2023 5:19:47 AM ExampleLogger main
SEVERE: An error occurred
java.lang.ArithmeticException: / by zero
 at ExampleLogger.main(ExampleLogger.java:17)

Feb 19, 2023 5:19:47 AM ExampleLogger main
SEVERE: An error occurred
java.lang.ArithmeticException: / by zero
 at ExampleLogger.main(ExampleLogger.java:17)
Feb 19, 2023 5:19:47 AM ExampleLogger main
INFO: Application finished.
Feb 19, 2023 5:19:47 AM ExampleLogger main
INFO: Application finished.

However, we saw duplicated messages on the console which is a common issue when using multiple Handlers. To avoid duplicated log messages, you can do either of the below at the beginning of the main method.

  1. remove the default ConsoleHandler that is attached to the root logger, or
  2. call LOGGER.setUseParentHandlers(false);

// Option 1: Remove the default ConsoleHandler :
Logger rootLogger = Logger.getLogger("");
Handler[] handlers = rootLogger.getHandlers();
for (Handler handler : handlers) {
    if (handler instanceof ConsoleHandler) {
        rootLogger.removeHandler(handler);
    }
}

// Option 2: call LOGGER.setUseParentHandlers(false);
LOGGER.setUseParentHandlers(false);
// Option 1: Remove the default ConsoleHandler :
Logger rootLogger = Logger.getLogger("");
Handler[] handlers = rootLogger.getHandlers();
for (Handler handler : handlers) {
    if (handler instanceof ConsoleHandler) {
        rootLogger.removeHandler(handler);
    }
}

// Option 2: call LOGGER.setUseParentHandlers(false);
LOGGER.setUseParentHandlers(false);

Using ConsoleHandler and FileHandler

There is a case when you want to log messages to both the console and file and possibly with different logging levels, here is how you can achieve it.

public class JULExample {
    private static final Logger LOGGER = Logger.getLogger(JULExample.class.getName());

    public static void main(String[] args) {
        LOGGER.setUseParentHandlers(false); // Disable default console handler
        ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setLevel(Level.INFO);
        LOGGER.addHandler(consoleHandler);

        try {
            FileHandler fileHandler = new FileHandler("mylog.log", true);
            fileHandler.setFormatter(new SimpleFormatter());
            fileHandler.setLevel(Level.WARNING);
            LOGGER.addHandler(fileHandler);
        } catch (IOException e) {
            LOGGER.severe("Failed to create log file: " + e.getMessage());
        }

        LOGGER.info("Starting application...");

        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            LOGGER.log(Level.SEVERE, "An error occurred", e);
        }

        LOGGER.warning("this is a warning message");
        LOGGER.info("Application finished.");
    }
}
public class JULExample {
    private static final Logger LOGGER = Logger.getLogger(JULExample.class.getName());

    public static void main(String[] args) {
        LOGGER.setUseParentHandlers(false); // Disable default console handler
        ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setLevel(Level.INFO);
        LOGGER.addHandler(consoleHandler);

        try {
            FileHandler fileHandler = new FileHandler("mylog.log", true);
            fileHandler.setFormatter(new SimpleFormatter());
            fileHandler.setLevel(Level.WARNING);
            LOGGER.addHandler(fileHandler);
        } catch (IOException e) {
            LOGGER.severe("Failed to create log file: " + e.getMessage());
        }

        LOGGER.info("Starting application...");

        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            LOGGER.log(Level.SEVERE, "An error occurred", e);
        }

        LOGGER.warning("this is a warning message");
        LOGGER.info("Application finished.");
    }
}

We attached two handlers to the LOGGER instance and each has its own logging level, and we also called LOGGER.setUseParentHandlers(false); to avoid duplicated messages on the console. When you run the code, you should be able to see the output on console (INFO and above are logged):

Feb 28, 2023 10:23:25 PM com.example.javasandbox.logging.JULExample main
INFO: Starting application...
Feb 28, 2023 10:23:25 PM com.example.javasandbox.logging.JULExample main
SEVERE: An error occurred
java.lang.ArithmeticException: / by zero
 at com.example.javasandbox.logging.JULExample.main(JULExample.java:74)

Feb 28, 2023 10:23:25 PM com.example.javasandbox.logging.JULExample main
WARNING: this is a warning message
Feb 28, 2023 10:23:25 PM com.example.javasandbox.logging.JULExample main
INFO: Application finished.
Feb 28, 2023 10:23:25 PM com.example.javasandbox.logging.JULExample main
INFO: Starting application...
Feb 28, 2023 10:23:25 PM com.example.javasandbox.logging.JULExample main
SEVERE: An error occurred
java.lang.ArithmeticException: / by zero
 at com.example.javasandbox.logging.JULExample.main(JULExample.java:74)

Feb 28, 2023 10:23:25 PM com.example.javasandbox.logging.JULExample main
WARNING: this is a warning message
Feb 28, 2023 10:23:25 PM com.example.javasandbox.logging.JULExample main
INFO: Application finished.

and the output in the file (WARN and above are logged)

Feb 28, 2023 10:23:25 PM com.example.javasandbox.logging.JULExample main
SEVERE: An error occurred
java.lang.ArithmeticException: / by zero
 at com.example.javasandbox.logging.JULExample.main(JULExample.java:74)

Feb 28, 2023 10:23:25 PM com.example.javasandbox.logging.JULExample main
WARNING: this is a warning message
Feb 28, 2023 10:23:25 PM com.example.javasandbox.logging.JULExample main
SEVERE: An error occurred
java.lang.ArithmeticException: / by zero
 at com.example.javasandbox.logging.JULExample.main(JULExample.java:74)

Feb 28, 2023 10:23:25 PM com.example.javasandbox.logging.JULExample main
WARNING: this is a warning message

Using configuration file

We can also use a configuration file to configure the behavior of java.util.logging. The configuration file is a properties file that specifies various settings for the logging system, such as log levels, log file locations, and formatting.

Here’s an example of a simple logging configuration file called jul.properties:

handlers= java.util.logging.ConsoleHandler
.level= INFO

# Set the console handler properties
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

## Set the logger level to WARNING
com.example.javasandbox.logging.JULExample.level = WARNING
handlers= java.util.logging.ConsoleHandler
.level= INFO

# Set the console handler properties
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

## Set the logger level to WARNING
com.example.javasandbox.logging.JULExample.level = WARNING

In this configuration file, we’ve set the default log level to INFO, and we’ve also configured a console handler to output log messages to the console. We’ve set the logger level for a specific class (com.example.javasandbox.logging.JULExample) to WARNING, which means that only messages with a level of WARNING or higher will be logged for that class.

Here’s an example of using the configuration file.

package com.example.javasandbox.logging;

public class JULExample {
    public static void main(String[] args) throws IOException {
        // Load the logging configuration file
        InputStream configStream = JULExample.class.getResourceAsStream("/jul.properties");
        LogManager.getLogManager().readConfiguration(configStream);

        // Get a logger for our application
        Logger logger = Logger.getLogger(JULExample.class.getName());

        // Log a message
        logger.finest("This is a FINEST message.");
        logger.finer("This is a FINER message.");
        logger.fine("This is a FINE message.");
        logger.config("This is a CONFIG message.");
        logger.info("This is an INFO message.");
        logger.warning("This is a WARNING message.");
        logger.severe("This is a SEVERE message.");
    }
}

/* we only see warning and above message
Mar 04, 2023 12:54:33 PM com.example.javasandbox.logging.JULExample main
WARNING: This is a WARNING message.
Mar 04, 2023 12:54:33 PM com.example.javasandbox.logging.JULExample main
SEVERE: This is a SEVERE message.
*/
package com.example.javasandbox.logging;

public class JULExample {
    public static void main(String[] args) throws IOException {
        // Load the logging configuration file
        InputStream configStream = JULExample.class.getResourceAsStream("/jul.properties");
        LogManager.getLogManager().readConfiguration(configStream);

        // Get a logger for our application
        Logger logger = Logger.getLogger(JULExample.class.getName());

        // Log a message
        logger.finest("This is a FINEST message.");
        logger.finer("This is a FINER message.");
        logger.fine("This is a FINE message.");
        logger.config("This is a CONFIG message.");
        logger.info("This is an INFO message.");
        logger.warning("This is a WARNING message.");
        logger.severe("This is a SEVERE message.");
    }
}

/* we only see warning and above message
Mar 04, 2023 12:54:33 PM com.example.javasandbox.logging.JULExample main
WARNING: This is a WARNING message.
Mar 04, 2023 12:54:33 PM com.example.javasandbox.logging.JULExample main
SEVERE: This is a SEVERE message.
*/

SLF4J

Before we learn other logging frameworks, it’s worth mentioning a special commonly used logging package, SLF4J — as it is often used along with other logging frameworks including the JUL we have just learned.

SLF4J is not a specific logging solution. It provides some Java logging APIs in facade pattern, similar to JCL. It was previously developed to replace JCL.

The core API provided by SLF4J is some interfaces and a LoggerFactory class. With SLF4J, you do not need to specify the logging system you plan to use in the code or configuration file. You can use a logging implementation scheme without modifying any configuration during deployment. During compilation, the real logging library is statically bound.

Using SLF4J without providing a logging framework

As SLF4J is commonly included in other logging frameworks, to demonstrate what happens if we don’t provide any logging framework, let’s introduce the dependency below.

implementation("org.slf4j:slf4j-api:1.7.26")
implementation("org.slf4j:slf4j-api:1.7.26")

And with the code below.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SLF4JExample {
    private static final Logger logger = LoggerFactory.getLogger(SLF4JExample.class);

    public static void main(String[] args) {
        logger.info("Hello, SLF4J!");
    }
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SLF4JExample {
    private static final Logger logger = LoggerFactory.getLogger(SLF4JExample.class);

    public static void main(String[] args) {
        logger.info("Hello, SLF4J!");
    }
}

When I ran the code, I saw the following error on my console and didn’t see the Hello SLF4J! message. It indicates that SLF4J was not able to find an implementation of the logging framework (actually I didn’t specify any logging framework)

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

SLF4J requires both the SLF4J API and an implementation of the API to be present on the classpath at runtime. If SLF4J cannot find a suitable implementation, it will default to a no-operation (NOP) implementation, which does not log anything.

If you don’t see the above error, it is probably because some logging implementations are included in your classpath. e.g. when you use SpringBoot, the logpack-class and slf4j-api are automatically included in spring-boot-starter and you can reproduce the error above by excluding it with exclude("org.springframework.boot", "spring-boot-starter-logging")

To fix the error, you need to include an implementation of SLF4J in your project’s dependencies. The specific implementation you choose will depend on your needs and preferences. Here are some common SLF4J implementations.

  • Logback: ch.qos.logback:logback-classic:1.2.3
  • Log4j2: org.apache.logging.log4j:log4j-slf4j-impl:2.17.1
  • JUL (Java Util Logging): org.slf4j:jul-to-slf4j:1.7.32

I will demonstrate how to use SLF4J in the following Logback and Log4J2 sections.

Logback

Logback is a reliable, universal, fast, and flexible Java logging framework. Logback consists of three modules: logback-core, logback-classic, and logback-access. logback-core is the base of the other two modules. logback-classic is an advanced version of Log4j that fully implements the SLF4J API.

logback-access integrates with servlet containers so that you can use it to write HTTP-access logs. Logback depends on the logback.xml configuration file and can also support the groovy format.

Let’s learn how to use Logback by completing the following tasks which are supposed to be very common in your daily development.

  1. Use SLF4J and Logback for logging
  2. Print the log to both stdout (console) and files
  3. Configure different logging levels for different packages
  4. Run our program in IDE (IntelliJ IDEA)
  5. Run our program with java command

Adding dependencies

As we mentioned earlier, we can use SLF4J as the logging API in your code, and then choose any compatible logging framework (here Logback) that you want to use at runtime. To use them in your code, you will need to add the following dependencies in your build.gralde.kts (gradle Kotlin DSL)

implementation("ch.qos.logback:logback-classic:1.2.3")
implementation("ch.qos.logback:logback-classic:1.2.3")

The logback-classic module includes the necessary bridge code to connect to the SLF4J API. Once you have the appropriate bridge or adapter in your dependencies, you can use SLF4J logging methods to write log messages, and the messages will be forwarded to the configured logging framework at runtime. As ch.qos.logback:logback-core and org.slf4j:slf4j-api are part of logback-classic, so they are included in the classpath automatically.

Configuring logback.xml

The program uses a default configuration file named logback.xml or logback-test.xml, which should be located in the classpath in our case, we put the file in java/main/resources.

If neither of these files is found on the classpath, logback will default to invoking BasicConfigurator which will set up a minimal configuration. This minimal configuration consists of a ConsoleAppender attached to the root logger. The output is formatted using a PatternLayoutEncoder set to the pattern %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} -%kvp- %msg%n. Moreover, by default the root logger is assigned the DEBUG level.

If you want to use a different configuration file, you can specify its location by setting the logback.configurationFile system property to the file path, like this:

java -Dlogback.configurationFile=/path/to/logback.xml
java -Dlogback.configurationFile=/path/to/logback.xml

You can set the system property programmatically in your application code, like this:

System.setProperty("logback.configurationFile", "/path/to/logback.xml");
System.setProperty("logback.configurationFile", "/path/to/logback.xml");

This should be done before Logback is initialized (i.e., before any logging calls are made). Once the system property is set, Logback will use the specified configuration file instead of the default one.

Let’s simply create a file to allow us

  • Print the log to both stdout (console) and files — by writing two appenders
  • Configure different logging levels for different packages — WARN level for com.example.javasandbox package.

<button data-code="

%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} – %msg%n

logback.log

%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} – %msg%n

” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

<configuration>
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="file" class="ch.qos.logback.core.FileAppender">
        <file>logback.log</file>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="console" />
        <appender-ref ref="file" />
    </root>

    <logger name="com.example.javasandbox" level="WARN" />
</configuration>
<configuration>
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="file" class="ch.qos.logback.core.FileAppender">
        <file>logback.log</file>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="console" />
        <appender-ref ref="file" />
    </root>

    <logger name="com.example.javasandbox" level="WARN" />
</configuration>

We defined the following elements:

  1. Two appenders: console and file which logs the messages to console and file respectively.
  2. A root logger: The root logger is typically used to set the default logging level for the entire application. By default, all log messages flow to the root logger, and then they are filtered and processed by loggers lower in the hierarchy, we bind the two appenders to it and set the logging level to INFO.
  3. A customized logger: it sets the logging level of the package (com.example.javasandbox) and its sub-package to WARN. (you can also bind an appender to it, let’s see in addition to printing to the console and logging to the file, you also want to log in to Kafak, then you can configure a Kafka appender and write below (the two appenders of root still applies to this logger)

<button data-code="

” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

<logger name="com.example.javasandbox" level="WARN">
    <appender-ref ref="kafka" />
</logger>
<logger name="com.example.javasandbox" level="WARN">
    <appender-ref ref="kafka" />
</logger>

Write the code

Let’s write the simple class JavaSandboxApplication printing different levels of logs. The LoggerFactory.getLogger gets our customized logger com.example.javasandbox as class JavaSandboxApplication sits in that package.

package com.example.javasandbox;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class JavaSandboxApplication {
    private static final Logger logger = LoggerFactory.getLogger(JavaSandboxApplication.class);
    public static void main(String[] args) {
        logger.trace("This is a trace message.");
        logger.debug("This is a debug message.");
        logger.info("This is an info message.");
        logger.warn("This is a warn message.");
        logger.error("This is an error message.");
    }
}
package com.example.javasandbox;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class JavaSandboxApplication {
    private static final Logger logger = LoggerFactory.getLogger(JavaSandboxApplication.class);
    public static void main(String[] args) {
        logger.trace("This is a trace message.");
        logger.debug("This is a debug message.");
        logger.info("This is an info message.");
        logger.warn("This is a warn message.");
        logger.error("This is an error message.");
    }
}

Run our application

We are all set, let’s run the code in IDEA first, we are able to see the following messages on our console and log file logback.log.

15:25:37.840 [main] WARN  c.e.j.JavaSandboxApplication - This is a warn message.
15:25:37.842 [main] ERROR c.e.j.JavaSandboxApplication - This is an error message.
15:25:37.840 [main] WARN  c.e.j.JavaSandboxApplication - This is a warn message.
15:25:37.842 [main] ERROR c.e.j.JavaSandboxApplication - This is an error message.

To run with java command (which you will probably do on production), let’s run the commands below, and then we will see the two messages printed to the console and written to the file logback.log.

$ ./gradlw build
BUILD SUCCESSFUL in 11s

$ java -jar build/libs/java-sandbox-0.0.1-SNAPSHOT.jar
$ ./gradlw build
BUILD SUCCESSFUL in 11s

$ java -jar build/libs/java-sandbox-0.0.1-SNAPSHOT.jar

We noticed even though we set our root logger’s level to INFO, we only saw WARN and ERROR because we set the level for our package explicitly. Similarly, you can configure different levels for different packages by just appending lines in the logpack.xml.

Wrap up

Let’s warp up what we have done so far, to use Logpack in our code, the common way is to use SLF4J as the API so that we don’t need to change our code even if we switch to other logging frameworks like log4j2. We can configure the logging behavior by using logback.xml.

Let’s see what happens if we rename logback.xml to logback-bk.xml. We will be able to see the following four messages instead of two which helped to confirm that the default log level DEBUG is applied, and no messages are appended to the file anymore.

15:40:18.920 [main] DEBUG com.example.javasandbox.JavaSandboxApplication - This is a debug message.
15:40:18.922 [main] INFO com.example.javasandbox.JavaSandboxApplication - This is an info message.
15:40:18.922 [main] WARN com.example.javasandbox.JavaSandboxApplication - This is a warn message.
15:40:18.922 [main] ERROR com.example.javasandbox.JavaSandboxApplication - This is an error message.
15:40:18.920 [main] DEBUG com.example.javasandbox.JavaSandboxApplication - This is a debug message.
15:40:18.922 [main] INFO com.example.javasandbox.JavaSandboxApplication - This is an info message.
15:40:18.922 [main] WARN com.example.javasandbox.JavaSandboxApplication - This is a warn message.
15:40:18.922 [main] ERROR com.example.javasandbox.JavaSandboxApplication - This is an error message.

If we run the app with the option below, we saw two messages on the console and file again!

java -Dlogback.configurationFile=src/main/resources/logback-bk.xml -jar build/libs/java-sandbox-0.0.1-SNAPSHOT.jar
java -Dlogback.configurationFile=src/main/resources/logback-bk.xml -jar build/libs/java-sandbox-0.0.1-SNAPSHOT.jar

Conclusion

In this first part of the Java Logging series, we learned that there are many options for developers to choose from when it comes to java logging. And we demonstrated how to use some of them including the combination Logback x SLFJ4 that is commonly used in real-world applications.

JUL is included in JDK so it doesn’t require any dependency for you to start logging your application, but it lacks flexibility and functionally, it is not generally used in production. A more sophisticated framework like logpack is generally a better choice.

In logpack, we generally use logpack.xml or logpack-test.xml to configure the behaviors or the logging in which you can use the root logger to set a default logging level for the entire application, or to add appenders that should be used for all log messages. However, it is generally recommended to create and use custom loggers lower in the hierarchy, as this allows you to configure logging behavior more precisely and target specific parts of the application.

Mastering Logging Frameworks Series

References