Java Logging Tutorials

Java Logging Tutorials

In this detailed Resource page, we feature an abundance of Java Logging Tutorials!

A Java logging framework is a computer data logging package for the Java platform.

Logging refers to the recording of activity. Logging is a common issue for development teams. Several frameworks ease and standardize the process of logging for the Java platform. This article covers general purpose logging frameworks.

Functionality overview

Logging is broken into three major pieces: the Logger, Formatter and the Handler (Appender). The Logger is responsible for capturing the message to be logged along with certain metadata and passing it to the logging framework. After receiving the message, the framework calls the Formatter with the message. The Formatter formats it for output. The framework then hands the formatted message to the appropriate Appender for disposition. This might include a console display, writing to disk, appending to a database, or email.

Simpler logging frameworks, like Java Logging Framework by the Object Guy, combine the logger and the appender. This simplifies default operation, but it is less configurable, especially if the project is moved across environments.

Logger

A Logger is an object that allows the application to log without regard to where the output is sent/stored. The application logs a message by passing an object or an object and an exception with an optional severity level to the logger object under a given a name/identifier.

Formatters or renderers

A Formatter is an object that formats a given object. Mostly this consists of taking the binary object and converting it to a string representation.

Appenders or handlers

Appenders listen for messages at or above a specified minimum severity level. The Appender takes the message it is passed and posts it appropriately. Message dispositions include:

  • display on the console
  • write to a file or syslog
  • append to a database table
  • distribute via Java Messaging Services
  • send via email
  • write to a socket
  • discard to the “bit-bucket” (/dev/null)

Feature comparison

FrameworkSupported log levelsStandard appendersPopularityCost / licence
Log4JFATAL ERROR WARN INFO DEBUG TRACEAsyncAppender, JDBCAppender, JMSAppender, LF5Appender, NTEventLogAppender, NullAppender, SMTPAppender, SocketAppender, SocketHubAppender, SyslogAppender, TelnetAppender, WriterAppenderWidely used in many projects and platformsApache License, Version 2.0
Java Logging APISEVERE WARNING INFO CONFIG FINE FINER FINESTSun’s default Java Virtual Machine (JVM) has the following: ConsoleHandler, FileHandler, SocketHandler, MemoryHandlerComes with the JRE
Apache Commons LoggingFATAL ERROR WARN INFO DEBUG TRACEDepends on the underlying frameworkWidely used, in conjunction with log4jApache License, Version 2.0
SLF4JERROR WARN INFO DEBUG TRACEDepends on the underlying framework, which is pluggableMIT License
tinylogERROR WARNING INFO DEBUG TRACEConsoleWriter, FileWriter, LogcatWriter, JdbcWriter, RollingFileWriter, SharedFileWriter and null (discards all log entries)Apache License, Version 2.0
LogbackERROR WARN INFO DEBUG TRACEToo many to list: see Appender JavaDocUsed in many projects like Akka, Apache Camel, Apache Cocoon, Artifactory, Gradle, Lift Framework, Play Framework, Scalatra, SonarQube, etc…LGPL, Version 2.1

Summary

Apache Commons Logging isn’t really a logging framework, but a wrapper for one. As such, it requires a logging framework underneath it. It is particularly useful when developing reusable libraries which need to write to whichever underlying logging system is being used by the application. It also provides flexibility in heterogeneous environments where the logging framework is likely to change, although in most cases, once a logging framework has been chosen, there is little need to change it over the life of the project.

The Java Logging API is also not a logging framework, but a standard API for accessing a logging framework. Compatible frameworks can be loaded into JVM and accessed via the API. There is also a logging implementation supplied with the Sun JVM which is the default logging framework accessed by the API. Many developers confuse this implementation with the Java Logging API.

Note
If you wish to build up your Java Logging knowledge first, check out our java.util.logging Example.

Java Logging Tutorials – Getting Started

Simple examples based on the Java Logging

  • Create a sequence of log files
    This is an example of how to create a sequence of log files.
  • Set size threshold of log file
    This is an example of how to set size threshold of a log file.
  • Log method call
    In this example we shall show you how to log a method call. We have implemented the LogMethodCall Class, with a simple method to log its messages.
  • Write Log entries to log file
    With this example we are going to demonstrate how to write Log entries to a log file.
  • Check if message is loggable
    This is an example of how to check if a message is loggable. We are going to use a Logger with logging.Level set to WARNING and then log messages in different levels, in order to check if they are loggable.
  • Prevent the logger send log messages to its parent logger
    With this example we are going to demonstrate how to prevent the logger from sending log messages to its parent logger. When a Logger is used, it keeps track of a parent Logger, which is its nearest existing ancestor in the Logger namespace. By default, the logger publishes to its parent’s Handler.
  • Conditional logging
    This is an example of how to use Conditional logging. Using conditional logging in a Class means that we check the Level for which the Logger is enabled before we log a message to that level. We have implemented a Class that uses a logger.
  • Log an exception
    With this example we are going to demonstrate how to log an exception. In order to do so, we will use a DateFormat and parse a String pattern to create a new Date.

Java Logging Tutorials – Functions

Learn the most famous functionalities and operations of Java Logging

  • Create custom Formatter for Logger handler
    In this example we shall show you how to create custom Formatter for a Logger‘s Handler. The Handler usually uses a Formatter associated with it to format LogRecords. The Formatter takes a LogRecord and converts it to a string.
  • Set Formatter for Logger handler
    With this example we are going to demonstrate how to set a Formatter for a Logger Handler. The Formatter is used by the Handler to format LogRecords. In short, to set a Formatter for a Logger’s handler you should
  • Set filter on Logger handler
    This is an example of how to set a filter on a Logger’s Handler. The Filter is used to provide control over what is logged, beyond the control that the levels provide. Each Logger and each Handler can have a filter associated with it.
  • Set logger log level
    With this example we are going to demonstrate how to set a Logger‘s log level. The Level defines a set of standard logging levels that can be used to control logging output. The standard levels are provided at the Level API.
  • Use Logger MemoryHandler class
    In this example we shall show you how to use the Logger MemoryHandler class. The MemoryHandler is a Handler that buffers requests in a circular buffer in memory.
  • Use of logger console handler
    In this example we shall show you how to use a logger’s ConsoleHandler. The ConsoleHandler is a handler that takes logs from a Logger and publishes them to System.err.
  • Compare Logger Level
    In this example we shall show you how to compare Logger Level. The logging Level is used to control logging output. Level objects, such as SEVERE, WARNING and INFO are ordered and specified by ordered integers.

Java Logging Tutorials – Integrations

Learn how to use Java Logging with other frameworks

SLF4J

  • SLF4J Tutorial for Beginners
    In this post, we feature a comprehensive SLF4J Tutorial in order to understand how it helps addresses the problem of logging in software world.
  • Slf4j Format String Example
    In this example, we are going to see how String log messages can be constructed in SLF4J with parameter substitution.
  • Slf4j Commons Logging Example
    In this example, we are going to see how SLF4J fares vis-à-vis Apache Commons Logging.
  • SLF4J Markers example
    In this example, we shall show you how to use Markers with SLF4J.
  • SLF4J Logging Levels Example
    This post is about the various logging levels available in SLF4J and how to extend it with Marker interface. This post utilizes Logback as the logging implementation for our examples.
  • Slf4j Configuration File Example
    In this example, we are going to see how to configure Slf4j with some popular logging frameworks. SLF4J is a facade or an abstraction layer over various logging frameworks.
  • Solving Failed to load class “org.slf4j.impl.StaticLoggerBinder” Error
    The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks (e.g. java.util.logging, logback, log4j). This allows the end user to plug in the desired logging framework at deployment time.
  • Slf4j Spring Boot Example
    In this example, we are going to learn how to use SLF4J in Spring projects with an example of Spring Boot application.

Logback

  • Logback File Appender Example
    In this example, we are going to show you how to record log messages in files using Logback framework. After a brief introduction to the overall Logback framework and File Appender in the Logback, we will discuss the implementation details of our example.
  • Logback Additivity Example
    If you use Logback or Log4j logging framework, you may come across some situations that you realize too much or too little log messages on the console or in a file. But you don’t actually understand how it happens. It is probably the consequence of the additivity attribute in the logging framework.
  • Logback AsyncAppender Example
    In this post, we feature a comprehensive Example on Logback AsyncAppender. Most of the Java applications rely on logging messages to identify and troubleshoot problems. Logback is one of the most widely used logging frameworks in the Java community.
  • Logback Change Log Level at Runtime Example
    In this post, we feature a comprehensive Example on Logback Change Log Level. Logback is one of the most widely used logging frameworks in the Java community.
  • Logback Configuration Example
    In this post, we are going to show you how to configure your application to use slf4j and logback as logger solution.
  • Logback Encoder Example
    In this example, we are going to discuss the Encoders in the Logback. In a few words, Encoders are responsible to convert the events into byte array. Logback, as a successor of the popular Log4j project, is designed to be the next generation logging framework with many advantages over other logging frameworks.
  • Logback File Appender Example
    In this example, we are going to show you how to record log messages in files using Logback framework. After a brief introduction to the overall Logback framework and File Appender in the Logback, we will discuss the implementation details of our example.
  • Logback Kafka Appender Example
    This article discusses Kafka as a logging destination for a Java application. In this tutorial, We will use logback as the logging framework.
  • Logback Mapped Diagnostic Contexts (MDC) Example
    In the client-server or web applications, log statements that belong to distinct client’s request are mixed and it is hard to trace them separately. The Mapped Diagnostic Context (MDC) in the Logback is a great way to differentiate them. In this post, we will explain the MDC and show you who to use it in the Logback.
  • Logback OutputStreamAppender Example
    This article discusses the OutputStreamAppender of logback, a logging framework for the Java application.
  • Logback RollingFileAppender Example
    In this example, we will begin by explaining the Logback RollingFileAppender and then move on to how to get RollingFileAppender running on simple examples. Logback is a modern, fast and flexible logging framework.
  • Logback Syslog Example
    In this post, we shall show you how to transmit logs to the Syslog server using Logback framework. After a brief introduction to Logback framework and Syslog protocol, we will look at the implementation details of our example.
  • Logback Tutorial for Beginners
    In this post, we feature a comprehensive Logback Tutorial. Logback is one of the most widely used logging frameworks in the Java community. It provides more options for configuration and more flexibility in archiving old log files.
  • Logback vs Log4j Example
    In this post, we feature a comprehensive Example on Logback vs Log4j. Logback and Log4j are the most widely used logging frameworks in the Java community. In this tutorial, I will demonstrate how to log the messages in Java applications with both Logback and Log4j.

Log4j

  • Log4j – Additivity Property Example
    In this post, we are going to discuss about log4j additivity and how you configure them using both log4j.properties and log4j.xml files.
  • Log4j – Appender Example
    In this post, we are going to discuss about log4j appenders and how you configure it using an log4j.xml file.
  • Log4j – Log Levels Example
    In this post, we are going to discuss about log4j levels and how you configure them using both log4j.properties and log4j.xml files.
  • Log4j BufferSize Example
    This article is a tutorial about log priority levels in Log4j. In this tutorial, we are going to configure log4j via property files.
  • Log4j ConsoleAppender Configuration Example
    In this example, we will try to show how to use the org.apache.log4j.ConsoleAppender to print the logs in the application console using the Log4j logging services.
  • Log4j Conversion Pattern Example
    In this tutorial, I will show you how to implement some useful Log4j Conversion Patterns for writing the logging mechanism in Java development.
  • Log4j Database Appenders Example
    In this example, we are going to learn how to log messages from our application into database with log4j.
  • Log4j Date Format Example
    This article is a tutorial about date format patterns in Log4j. In this tutorial, we are going to configure log4j via property files.
  • Log4j Email Configuration Example
    In this tutorial, I will show you how to implement an out of box Log4j appender (called as SMTPAppender) to send email alerts.
  • Log4j Enable/Disable Logging Example
    In this tutorial, I will show you how to enable or disable the Log4j mechanism through a simple web application.
  • Log4j ImmediateFlush Property Example
    This article is a tutorial about log priority levels in Log4j. In this tutorial, we are going to configure log4j via property files.
  • Log4j Priority Example
    This article is a tutorial about log priority levels in Log4j. In this tutorial, we are going to configure log4j via property files.
  • log4j properties example
    This is an example of how to configure log4j, using the log4j.properties file. Log4j is a logging library for Java, licensed under the Apache Software Foundation. It is a Logging Framework that is thread-safe and flexible, thanks to its configuration.
  • Log4j Property Configuration Example
    Log4J is an open source project which allows developers output log statements with configured granularity. The configuration can be maintained by the configuration files (XML, Property). Log4J has three main components: Loggers, Appenders and Layouts.
  • Log4j Rolling Daily File Example
    Logging is a critical feature of any application. In this tutorial, I will show you how to implement some useful Log4j RollingFileAppender Patterns for writing the logging mechanism in Java development.
  • log4j rootlogger example
    In this example we shall talk about the rootlogger, which is a basic component in Log4j. Log4j a thread-safe and flexible logging library for Java, licensed under the Apache Software Foundation.
  • Log4j Rotation Example
    This article is a tutorial about log rotation in Log4j. In this tutorial, we are going to configure log4j via property files.
  • Log4j Specific File Location Example
    This article is a tutorial about logging to files in specific location. We will first checkout other logging methods and then proceed to log to a specific location.
  • Log4j writing to Different Log Files Example
    Logging is a critical feature of any application. In this tutorial, I will show you how to configure the Log4j to write logs to multiple files based on the category. To achieve this in our tutorial, we would be using the LevelRangeFilter.
  • Log4j XML Configuration Example
    In this example we will see how to configure Log4j using XML. You can use the property file as well but now  days xml is preferred over property file. Note that unlike Log4j 1.x, the public Log4j 2 API does not expose methods to add, modify or remove appenders and filters or manipulate the configuration in any way.
  • Logging System.out.println Results in a Log File Example
    In this example, we will try to show how to redirect the System.out.println() to a log file using Log4j logging services.
  • Log4j 2 Best Practices Example
    Logging is a critical feature of any application. In this tutorial, we will cover some Log4j2 best practices that can help developers get started and improve the logging with Log4j2.
  • Log4j 2 Getting Started Example
    In this tutorial, we will show you how to configure the Log4j2 with log4j2.xml file and print the logging to the console and a file.
  • Log4j 2 RollingFileAppender example
    In this example we shall talk about the RollingFileAppender, one of the most basic appenders of Log4j. Log4j a thread-safe and flexible logging library for Java, licensed under the Apache Software Foundation.

Tinilog

  • Simplify your logging with tinylog 1.0
    This article will show the differences as well as the similarities to Log4j and Logback and give a brief introduction in tinylog.
  • Improve your Logging in your Java EE Application with tinylog 1.1
    tinylog is a lightweight logging framework for Java. In opposite to Apache Log4j and Logback, tinylog consists of a single JAR file of only 80KB without any dependencies and has a static logger class. This means that you haven’t to use any boilerplate code for creating a logger instance for each class.

Other

  • Jetty Logging Configuration Example
    In this example, we will discuss logging capabilities of Jetty. We will first enable the logging module in Jetty and configure it afterwards. As in the previous Jetty examples, we will start with standalone Jetty; thereafter we will configure logging for Embedded Jetty server too.
  • Struts 2 and Log4J Example
    In this example we will learn how to integrate Struts2 application with Log4j logging framework. Apache Struts is a free, open-source, MVC framework for creating elegant, modern Java web applications.
  • Hibernate SQL Parameter Values using Log4j Example
    In this tutorial, we will demonstrate the use of Log4j to display the real-time SQL parameter values.
  • JSF 2 and Log4j Integration Example
    Log4j is a popular and widely-used logging framework for the Java development. It’s pretty easy to setup and use the Log4j mechanism in a JSF application. In this tutorial, I will show you how to implement the logging functionality with the JSF framework.
  • Hibernate Logging Configuration – SLF4J + Log4j and Logback
    In this example we are going to see how to configure Logging in Hibernate. SLF4J (Simple Logging Facade for Java) is a very nice logging framework that Hibernate uses, in order to output your logs using your favorite logging tool ( log4j, JCL, JDK logging, logback) to your preferred location.
  • JAX-WS Logging with Handler Example
    In this post, we feature a comprehensive Example on JAX-WS Logging with Handler. Java API for XML Web Services (JAX-WS) is a Java programming language for creating web services, particularly SOAP services. JAX-WS 2.0 specification was introduced in 2005 and has become part of JDK since JDK6.
  • JBoss WildfFly Logging Configuration Example
    In this example we will review the WildFly logging subsystems. We will apply the configuration to a Web application to generate a separate log files for our application instead of writing it to default server log file.
  • Play! Framework Logging Example
    Logging is a really important feature every application must have. Without it, it’s nearly impossible to know what your application is doing, how long does it take it, if it is failing, and if it is, why.
  • org.apache.commons.logging.logfactory Example
    In this example, we shall be talking about how we can use the Apache commons org.apache.commons.logging.Logfactory class.You can download the apache commons logging Jar file from here.The Logfactory class uses the Factory Design Pattern to select a logger class.

[undereg]

Back to top button