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

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">Swing (Java)</span> Java-based GUI toolkit

Swing is a GUI widget toolkit for Java. It is part of Oracle's Java Foundation Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs.

<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.

<span class="mw-page-title-main">Dependency injection</span> Software programming technique

In software engineering, dependency injection is a programming technique in which an object or function receives other objects or functions that it requires, as opposed to creating them internally. Dependency injection aims to separate the concerns of constructing objects and using them, leading to loosely coupled programs. The pattern ensures that an object or function that wants to use a given service should not have to know how to construct those services. Instead, the receiving 'client' is provided with its dependencies by external code, which it is not aware of. Dependency injection makes implicit dependencies explicit and helps solve the following problems:

In computing, syslog is a standard for message logging. It allows separation of the software that generates messages, the system that stores them, and the software that reports and analyzes them. Each message is labeled with a facility code, indicating the type of system generating the message, and is assigned a severity level.

<span class="mw-page-title-main">Apache Axis</span> Web service framework

Apache Axis is an open-source, XML based Web service framework. It consists of a Java and a C++ implementation of the SOAP server, and various utilities and APIs for generating and deploying Web service applications. Using Apache Axis, developers can create interoperable, distributed computing applications. Axis development takes place under the auspices of the Apache Software Foundation.

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.

In the Java computer programming language, an annotation is a form of syntactic metadata that can be added to Java source code. Classes, methods, variables, parameters and Java packages may be annotated. Like Javadoc tags, Java annotations can be read from source files. Unlike Javadoc tags, Java annotations can also be embedded in and read from Java class files generated by the Java compiler. This allows annotations to be retained by the Java virtual machine at run-time and read via reflection. It is possible to create meta-annotations out of the existing ones in Java.

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. The framework does not impose any specific programming model.. The framework has become popular in the Java community as an addition to the Enterprise JavaBeans (EJB) model. The Spring Framework is free and open source software.

Sun's Java Device Test Suite (JDTS) is the de facto industry-standard tool for assessing the quality of Java Platform, Micro Edition implementations. This tool performs quality testing for devices using the Java ME platform. A feature that distinguishes the Java Device Test Suite from Technology Compatibility Kit (TCKs) is its focus on an implementation's quality instead of an implementation's specification compliance.

Component Object Model (COM) is a binary-interface technology for software components from Microsoft that enables using objects in a language-neutral way between different programming languages, programming contexts, processes and machines.

<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.

<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.

JSON streaming comprises communications protocols to delimit JSON objects built upon lower-level stream-oriented protocols, that ensures individual JSON objects are recognized, when the server and clients use the same one. This is necessary as JSON is a non-concatenative protocol.

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". Archived from the original on April 15, 2013.
  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