Java logging framework

Last updated

A Java logging framework is a computer data logging package for the Java platform. This article covers general purpose logging frameworks.

Contents

Logging refers to the recording of activity by an application and is a common issue for development teams. Logging frameworks ease and standardize the process of logging for the Java platform. In particular they provide flexibility by avoiding explicit output to the console (see Appender below). Where logs are written becomes independent of the code and can be customized at runtime.

Unfortunately the JDK did not include logging in its original release so by the time the Java Logging API was added several other logging frameworks had become widely used – in particular Apache Commons Logging (also known as Java Commons Logging or JCL) and Log4j. This led to problems when integrating different third-party libraries (JARs) each using different logging frameworks. Pluggable logging frameworks (wrappers) were developed to solve this problem.

Functionality overview

Logging is typically broken into three major pieces: the Logger, the Formatter and the Appender (or Handler).

Simpler logging frameworks, like 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 name/identifier.

Name

A logger has a name. The name is usually structured hierarchically, with periods (.) separating the levels. A common scheme is to use the name of the class or package that is doing the logging. Both Log4j and the Java logging API support defining handlers higher up the hierarchy.

For example, the logger might be named "com.sun.some.UsefulClass". The handler can be defined for any of the following:

  • com
  • com.sun
  • com.sun.some
  • com.sun.some.UsefulClass

As long as there is a handler defined somewhere in this stack, logging may occur. For example a message logged to the com.sun.some.UsefulClass logger, may get written by the com.sun handler. Typically there is a global handler that receives and processes messages generated by any logger.

Severity level

The message is logged at a certain level. Common level names are copied from Apache Commons Logging (although the Java Logging API defines different level names):

Common levels
LevelDescription
FATALSevere errors that cause premature termination. Expect these to be immediately visible on a status console.
ERROROther runtime errors or unexpected conditions. Expect these to be immediately visible on a status console.
WARNINGUse of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". Expect these to be immediately visible on a status console.
INFOInteresting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum.
DEBUGdetailed information on the flow through the system. Expect these to be written to logs only.
TRACEmore detailed information. Expect these to be written to logs only.

The logging framework maintains the current logging level for each logger. The logging level can be set more or less restrictive. For example, if the logging level is set to "WARNING", then all messages of that level or higher are logged: ERROR and FATAL.

Severity levels can be assigned to both loggers and appenders. Both must be enabled for a given severity level for output to be generated. So a logger enabled for debug output will not generate output if the handler that gets the message is not also enabled for debug.

Filters

Filters cause a log event to be ignored or logged. The most commonly used filter is the logging level documented in the previous section. Logging frameworks such as Log4j 2 and SLF4J also provide Markers, which when attached to a log event can also be used for filtering. Filters can also be used to accept or deny log events based on exceptions being thrown, data within the log message, data in a ThreadLocal that is exposed through the logging API, or a variety of other methods.

Formatters, Layouts 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. Each framework defines a default output format that can be overridden if desired.

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:

Feature comparison

Table 1 - Features
FrameworkTypeSupported Log LevelsStandard AppendersCommentsCost / Licence
Log4jLogging FrameworkFATAL ERROR WARN INFO DEBUG TRACEToo many to list: See Appender Documentation Widely used in many projects and platforms. Log4j 1 was declared "End of Life" in 2015 and has been replaced with Log4j 2 which provides an API that can be used with other logging implementations as well as an implementation of that API.
Apache License, Version 2.0
Java Logging API Logging FrameworkSEVERE WARNING INFO CONFIG FINE FINER FINESTSun's default Java Virtual Machine (JVM) has the following: ConsoleHandler, FileHandler, SocketHandler, MemoryHandlerComes with the JRE
tinylog Logging FrameworkERROR WARNING INFO DEBUG TRACEConsoleWriter, FileWriter, LogcatWriter, JdbcWriter, RollingFileWriter, SharedFileWriter and null (discards all log entries) [1] Apache License, Version 2.0
Logback Logging FrameworkERROR WARN INFO DEBUG TRACEToo many to list: see Appender JavaDoc Developed as a replacement for Log4j, with many improvements. Used by numerous projects, typically behind slf4j, for example Akka, Apache Camel, Apache Cocoon, Artifactory, Gradle, Lift Framework, Play Framework, Scalatra, SonarQube, Spring Boot, ... LGPL, Version 2.1
Apache Commons Logging (JCL)Logging WrapperFATAL ERROR WARN INFO DEBUG TRACEDepends on the underlying frameworkWidely used, often in conjunction with Log4jApache License, Version 2.0
SLF4J Logging WrapperERROR WARN INFO DEBUG TRACEDepends on the underlying framework, which is pluggable. Provides API compatible shims for JCL, JDK and Log4j logging packages. It can also use any of them to generate output. Defaults to using Logback for output if available.Widely used in many projects and platforms, frequently with Logback as the implementation. MIT License

Considerations

JCL and Log4j are very common simply because they have been around for so long and were the only choices for a long time. The flexibility of slf4j (using Logback underneath) has made it a popular choice.

SLF4J is a set of logging wrappers (or shims) that allow it to imitate any of the other frameworks. Thus multiple third-party libraries can be incorporated into an application, regardless of the logging framework each has chosen to use. However all logging output is generated in a standard way, typically via Logback.

Log4j 2 provides both an API and an implementation. The API can be routed to other logging implementations equivalent to how SLF4J works. Unlike SLF4J, the Log4j 2 API logs Message [2] objects instead of Strings for extra flexibility and also supports Java Lambda expressions. [3]

JCL isn't really a logging framework, but a wrapper for one. As such, it requires a logging framework underneath it, although it can default to using its own SimpleLog logger.

JCL, SLF4J and the Log4j 2 API are useful when developing reusable libraries which need to write to whichever underlying logging system is being used by the application. This 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. SLF4J and Log4j 2 benefit from being newer and build on the lessons learned from older frameworks. Moreover JCL has known problems with class-loaders when determining what logging library it should wrap [4] which has now replaced JCL. [5]

The Java Logging API is provided with Java. Although the API is technically separate from the default implementation provided with Java, replacing it with an alternate implementation can be challenging so many developers confuse this implementation with the Java Logging API. Configuration is by external files only which is not easily changed on the fly (other frameworks support programmatic configuration). The default implementation only provides a few Handlers and Formatters which means most users will have to write their own. [6]

See also

Related Research Articles

<span class="mw-page-title-main">Document Object Model</span> Convention for representing and interacting with objects in HTML, XHTML and XML documents

The Document Object Model (DOM) is a cross-platform and language-independent interface that treats an XML or HTML document as a tree structure wherein each node is an object representing a part of the document. The DOM represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects. DOM methods allow programmatic access to the tree; with them one can change the structure, style or content of a document. Nodes can have event handlers attached to them. Once an event is triggered, the event handlers get executed.

Java Platform, Standard Edition is a computing platform for development and deployment of portable code for desktop and server environments. Java SE was formerly known as Java 2 Platform, Standard Edition (J2SE).

The bridge pattern is a design pattern used in software engineering that is meant to "decouple an abstraction from its implementation so that the two can vary independently", introduced by the Gang of Four. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.

<span class="mw-page-title-main">Java syntax</span> Set of rules defining correctly structured program

The syntax of Java is the set of rules defining how a Java program is written and interpreted.

Hibernate ORM is an object–relational mapping tool for the Java programming language. It provides a framework for mapping an object-oriented domain model to a relational database. Hibernate handles object–relational impedance mismatch problems by replacing direct, persistent database accesses with high-level object handling functions.

Apache Wicket, commonly referred to as Wicket, is a component-based web application framework for the Java programming language conceptually similar to JavaServer Faces and Tapestry. It was originally written by Jonathan Locke in April 2004. Version 1.0 was released in June 2005. It graduated into an Apache top-level project in June 2007.

XML Interface for Network Services (XINS) is an open-source technology for definition and implementation of internet applications, which enforces a specification-oriented approach.

<span class="mw-page-title-main">Log4j</span> Java-based logging software

Apache Log4j is a Java-based logging utility originally written by Ceki Gülcü. It is part of the Apache Logging Services, a project of the Apache Software Foundation. Log4j is one of several Java logging frameworks.

The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Although the framework does not impose any specific programming model, it has become popular in the Java community as an addition to the Enterprise JavaBeans (EJB) model. The Spring Framework is open source.

The Java Class Library (JCL) is a set of dynamically loadable libraries that Java Virtual Machine (JVM) languages can call at run time. Because the Java Platform is not dependent on a specific operating system, applications cannot rely on any of the platform-native libraries. Instead, the Java Platform provides a comprehensive set of standard class libraries, containing the functions common to modern operating systems.

Within computing, Jakarta Activation is a Jakarta EE API that enables developers to:

Domain-driven design (DDD) is a major software design approach, focusing on modeling software to match a domain according to input from that domain's experts.

<span class="mw-page-title-main">SLF4J</span>

Simple Logging Facade for Java (SLF4J) provides a Java logging API by means of a simple facade pattern. The underlying logging backend is determined at runtime by adding the desired binding to the classpath and may be the standard Sun Java logging package java.util.logging, Log4j, Reload4j, Logback or tinylog.

In object-oriented design, the chain-of-responsibility pattern is a behavioral design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.

<span class="mw-page-title-main">Spring Roo</span> Open-source software tool

Spring Roo is an open-source software tool that uses convention-over-configuration principles to provide rapid application development of Java-based enterprise software. The resulting applications use common Java technologies such as Spring Framework, Java Persistence API, Thymeleaf, Apache Maven and AspectJ. Spring Roo is a member of the Spring portfolio of projects.

The Application Interface Specification (AIS) is a collection of open specifications that define the application programming interfaces (APIs) for high-availability application computer software. It is developed and published by the Service Availability Forum and made freely available. Besides reducing the complexity of high-availability applications and shortening development time, the specifications intended to ease the portability of applications between different middleware implementations and to admit third party developers to a field that was highly proprietary in the past.

Canigó is the name chosen for the Java EE framework of the Generalitat de Catalunya.

This article compares the application programming interfaces (APIs) and virtual machines (VMs) of the programming language Java and operating system Android.

Apache Commons Logging is a Java-based logging utility and a programming model for logging and for other toolkits. It provides APIs, log implementations, and wrapper implementations over some other tools.

References

  1. "User manual of tinylog".[ permanent dead link ]
  2. Log4j2 API Messages
  3. Java 8 Lambda support for lazy logging
  4. Avoiding Commons Logging
  5. Spring Logging Overview
  6. java.util.logging Overview