Java logging framework: Difference between revisions

Content deleted Content added
M0smith (talk | contribs)
GreenC bot (talk | contribs)
Rescued 1 archive link; reformat 1 link. Wayback Medic 2.5 per Category:All articles with dead external links - pass 3
 
(181 intermediate revisions by more than 100 users not shown)
Line 1:
{{Multiple issues|
==Introduction ot Java Logging Frameworks==
{{refimprove|date=June 2008}}
[[data logging|Logging]] is a common issue for most development teams. There have been several frameworks developed to ease and standardize the process of logging for the [[Java platform|Java platform]]. This page covers general purpose logging frameworks. There are other logging frameworks, toolkits and libraries like [http://aopclsuite.sourceforge.net/tracing.html Tracing Class Loader] but that is for another topic.
{{original research|date=June 2008}}
==Functionality Overview==
}}
Logging a message is broken into three major pieces:the Logger, Formatter and the Appender (Handler). The Logger is responsible for capturing the message to be logger, along with certain meta-data like level, and passing that to the logging framework. After receiving the message, the logging framework calls the Formatter on the message. The Formatter accepts and object and formats it for proper logging. The logging framework then hands the formatted message to the appropriate Appender to dispostion of the message. This might include displaying on a console, writing to disk, appending to a database, or notification via email.
 
A '''Java logging framework''' is a [[computer data logging]] package for the [[Java platform]]. This article covers general purpose logging frameworks.
 
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 [[Java Development Kit|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 [http://commons.apache.org/logging 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).
 
* 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 which formats it for output.
* The framework then hands the formatted message to the appropriate Appender/Handler for disposition. This might include output to a console display, writing to disk, appending to a database, or generating an email.
 
Simpler logging frameworks, like [https://web.archive.org/web/20020602114537/http://www.theobjectguy.com/javalog/ |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.
 
Simpler logging frameworks, like Java Logging Framework by the Object Guy, combine the logger and the appender together. This makes for simple initial configuration, but less configurable, especially as the project is moved across environments.
===Logger===
Most frameworks support a the notion of a Logger. A Logger is an object that allows the application to log data without regard to where the dataoutput is actually loggedsent/stored. The application logs a message inby the form ofpassing an object or andan object and andan [[Exception handling|exception.]] When a Logger is created, it is given a name orwith an identifier.optional severity Whenlevel loggingto athe message,logger itobject is logged atunder a certaingiven level or priorityname/identifier.
 
====Name====
A logger has a name. The name is usually hierarchicalstructured hierarchically, with periods (.) separating the levels. A common naming scheme is to use the name of the class or package that is doing the loggingslogging. Both log4jLog4j and the Java logging [[API]] supportedsupport defining Handlershandlers higher up the hierarchy.
 
For example, the logger might be named "<code>com.sun.some.UsefulClass</code>". The handler can be definedefined for any of the following:
* <code>com</code>
* <code>com.sun</code>
* <code>com.sun.some</code>
* <code>com.sun.some.UsefulClass</code>
 
As long as there is a handler defined somewhere in this stack, logging may occur. For example a message logged to the <code>com.sun.some.UsefulClass</code> logger, may get written by the <code>com.sun</code> handler. Typically there is a global handler that receives and processes messages generated by any logger.
====Level====
 
The message is logged at a certain level. The common levels are, copied from [http://jakarta.apache.org/commons/logging/guide.html#Message_Priorities_Levels Jakarta Commons Logging]:
==== Severity level ====
{| border=1 cellspacing=0 cellpadding=5
The message is logged at a certain level. Common level names are copied from [http://commons.apache.org/logging/guide.html#Message%20Priorities/Levels Apache Commons Logging] (although the Java Logging API defines different level names):
|FATAL
 
{| class="wikitable"
|+ '''Common levels'''
! Level
! Description
|-
|'''FATAL'''
|Severe errors that cause premature termination. Expect these to be immediately visible on a status console.
|-
|'''ERROR'''
|Other runtime errors or unexpected conditions. Expect these to be immediately visible on a status console.
|-
|'''WARNING'''
|Use 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.
|-
|'''INFO'''
|Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum.
|-
|'''DEBUG'''
|detailed information on the flow through the system. Expect these to be written to logs only.
|-
|'''TRACE'''
|more 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.
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.
===Formatters or Renderers===
 
A Formatter is an object that formats a given object for logging by the Appender. Mostly this consists of takeing the object and converting it to a string representation.
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.
===Appenders or Handlers===
 
The appenders are configured to listen for messages of a certain log level or above. The Appender takes the message it is passed and disposes of the messages. Some message dispositions include:
===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:
* display on the console
* write to a file or syslog
* append to a database table
* distribute via JMS[[Java messaging service|Java Messaging Services]]
* send via email
* write to a listening socket
* discard to the "bit-bucket" (/dev/null)
 
=== Feature comparison ===
==Best Practices==
{| class="wikitable" style="vertical-align: top;"
==Comparing Features==
|+ '''Table 1 - Features'''
{| border=1
! Framework
| ''Feature''
! Type
| ''Log4J''
! Supported Log Levels
| ''Java Logging API''
! Standard Appenders
| ''Jakarta Commons Logging''
! Comments
! Cost / Licence
|-
! Log4j
| Supported log levels
| Logging Framework
|FATAL ERROR WARN INFO DEBUG TRACE
| <code>FATAL ERROR WARN INFO DEBUG TRACE</code>
|SEVERE WARNING INFO CONFIG FINE FINER FINEST
| Too many to list: See [http://logging.apache.org/log4j/2.x/manual/appenders.html Appender Documentation]
|FATAL ERROR WARN INFO DEBUG TRACE
| 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.
| <div style="width: 8em;">Apache License, Version 2.0 </div>
|-
! [http://java.sun.com/javase/6/docs/technotes/guides/logging/ Java Logging API]
|Standard Appenders
| Logging Framework
|AsyncAppender, JDBCAppender, JMSAppender, LF5Appender, NTEventLogAppender, NullAppender, NullAppender, SMTPAppender, SocketAppender, SocketHubAppender, SyslogAppender, TelnetAppender, WriterAppender
| <code>SEVERE WARNING INFO CONFIG FINE FINER FINEST</code>
|ConsoleHandler, FileHandler, SocketHandler, MemoryHandler
| Sun's default Java Virtual Machine (JVM) has the following: ConsoleHandler, FileHandler, SocketHandler, MemoryHandler
|Depends on the underlying framework
|
| Comes with the JRE
|-
! [http://www.tinylog.org/ tinylog]
|Popularity
| Logging Framework
|Widely used in many project and platforms
| <code>ERROR WARNING INFO DEBUG TRACE</code>
|few
| ConsoleWriter, FileWriter, LogcatWriter, JdbcWriter, RollingFileWriter, SharedFileWriter and ''null'' (discards all log entries) <ref>{{cite web|title=User manual of tinylog|url=http://www.tinylog.org/user-manual|archive-url=https://archive.today/20130415233343/http://www.tinylog.org/user-manual|url-status=dead|archive-date=April 15, 2013}}</ref>
|many, in conjunction wiht log4j
|
| Apache License, Version 2.0
|-
! [http://logback.qos.ch/ Logback]
| Cost/Licence
| Logging Framework
|Apache License, Version 2.0
| <code>ERROR WARN INFO DEBUG TRACE</code>
|Comes with the JRE
| Too many to list: see [http://logback.qos.ch/apidocs/ch/qos/logback/core/Appender.html Appender JavaDoc]
|Apache License, Version 2.0
| Developed as a replacement for Log4j, with many improvements. Used by numerous projects, typically behind slf4j, for example [[Akka (toolkit)|Akka]], [[Apache Camel]], [[Apache Cocoon]], [[Artifactory]], [[Gradle]], [[Lift (web framework)|Lift Framework]], [[Play Framework]], [[Scalatra]], [[SonarQube]], [[Spring_Framework#Spring_Boot|Spring Boot]], ...
| [[LGPL]], Version 2.1
|-
! [[Apache Commons Logging]] (JCL)
|Recommendation
| Logging Wrapper
|The defacto standard, tried and true.
| <code>FATAL ERROR WARN INFO DEBUG TRACE</code>
|The new standard, just not there yet
|Use onlyDepends if you need an abstraction fromon the real loggingunderlying framework.
| Widely used, often in conjunction with Log4j
| Apache License, Version 2.0
|-
! [[SLF4J]]
| Logging Wrapper
| <code>ERROR WARN INFO DEBUG TRACE</code>
| Depends on the underlying framework, which is pluggable. Provides API compatible [[Shim_(computing)|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]]
|}
 
==SummaryConsiderations==
 
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.
Of the major players, log4j is still the front runner in the Java Logging ___domain. The log4j project has been around for a long time and has lots of supported from the development community. Its simple to implement, yet has powerful tools built to accomplish most logging tasks. It is also easily extendible to handle proprietary needs.
 
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.
The newer logging API which has been included in the JRE since 1.4, incorporates many of the same concepts as log4j. It has loggers and eppenders. However, log4j has been much more broadly used and there are mnay out-of-the-box solutions in log4j that are lacking in the Java Logging API.
 
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<ref>[http://logging.apache.org/log4j/2.x/manual/messages.html Log4j2 API Messages]</ref> objects instead of Strings for extra flexibility and also supports Java Lambda expressions.<ref>[http://logging.apache.org/log4j/2.x/manual/api.html#LambdaSupport Java 8 Lambda support for lazy logging]</ref>
The Jakarata Commons Logging isn't really a logging framework, but a logging fraemwork wrapper. As such, it requires a logging framework underneath it. It would be useful in an heterogeneous environment where the logging framework is likely to change. However, in most cases, once a suitable logging framework has been chosen, there is little need to change it over the life of the project.
 
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 <code>SimpleLog</code> logger.
==Links to Java Logging Projects==
 
* [http://java.sun.com/j2se/1.4.2/docs/guide/util/logging/overview.html Java Logging API]
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 <ref>[https://docs.spring.io/spring/docs/4.3.x/spring-framework-reference/html/overview.html#overview-avoiding-commons-logging Avoiding Commons Logging]</ref> which has now replaced JCL.<ref>[https://docs.spring.io/spring/docs/5.0.0.RC3/spring-framework-reference/overview.html#overview-logging Spring Logging Overview]</ref>
 
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.<ref>[https://docs.oracle.com/javase/8/docs/api/java/util/logging/package-summary.html java.util.logging Overview]</ref>
 
==See also==
*[[SLF4J]]
*[[Log4j]]
*[[logback]]
*[[Javolution]] LogContext based on [http://javolution.org/apidocs/javolution/context/package-summary.html#package_description context programming] (actual logging framework selectable at run-time).
*[[Runtime intelligence]]
 
==References==
{{Reflist}}
 
==External links==
* [http://java.sun.com/javase/6/docs/technotes/guides/logging/ Java 6.0 Logging API]
* [http://jakarta.apache.org/commons/logging/ Commons Logging]
* [[Log4j]]
* [http://protomatter.sourceforge.net Protomatter]
* [http://wwwjava-source.theobjectguy.comnet/javalogopen-source/logging JavaOpen Source Logging Framework]Tools byin the Object GuyJava]
* [http://apache.org/licenses/LICENSE-2.0 The Apache 2.0 license.]
 
* [http://logback.qos.ch/ Logback - A successor to the popular Log4j project]
See also [http://java-source.net/open-source/logging Open Source Logging Tools in Java]
* [http://www.tinylog.org/ tinylog - Minimalist logging utility with a static logger]
* [http://loggifier.unkrig.de Loggifier] A tool that inserts logging code into .class, .jar and .ear files
* [https://github.com/rdiachenko/jlv JLV - Java logging viewer which is currently available as a plugin for Eclipse IDE]
* [http://www.javavillage.in/perf4j.php Perf4j]
* [http://www.javavillage.in/slf4j.php SLF4J]
* [http://logging.apache.org/log4j/2.x/ Log4j 2]
 
{{DEFAULTSORT:Java Logging Framework}}
[[Category:Java platform]]
[[Category:Computer logging]]