Welcome!

Java IoT Authors: Liz McMillan, Elizabeth White, Pat Romanski, Stackify Blog, Progress Blog

Related Topics: Java IoT

Java IoT: Article

Cover Story: Log4j vs java.util.logging

Which Logging Library Is Better For You?

Are your Java programs littered with a multitude of randomly placed System.out.println statements and stack traces? When you add debugging messages to a class in a project, are the outputs of your messages interleaved among dozens of messages from other developers, making your messages difficult to read? Do you use a simple, hand-rolled logging API, and fear that it may not provide the flexibility and power that you need once your applications are in production? If you answered yes to any of the above questions, it's time for you to pick an industrial-strength logging API and start using it.

This article will help you choose a logging API by evaluating two of the most widely used Java logging libraries: the Apache Group's Log4j and the java.util.logging package (referred to as "JUL"). This article examines how each library approaches logging, evaluates their differences and similarities, and offers a few simple guidelines that will help you decide which library to choose.

Introduction to Log4j
Log4j is an open source logging library developed as a subproject of the Apache Software Foundation's Logging Services Project. Based on a logging library developed at IBM in the late 1990s, its first versions appeared in 1999. Log4j is widely used in the open source community, including by some big name projects such as JBoss and Hibernate.

Log4j's architecture is built around three main concepts: loggers, appenders, and layouts. These concepts allow developers to log messages according to their type and priority, and to control where messages end up and how they look when they get there. Loggers are objects that your applications first call on to initiate the logging of a message. When given a message to log, loggers generate Logging-Event objects to wrap the given message. The loggers then hand off the LoggingEvents to their associated appenders. Appenders send the information contained by the LoggingEvents to specified output destinations - for example, a ConsoleAppender will write the information to System.out, or a FileApppender will append it to a log file. Before sending LoggingEvent information to its final output target, some appenders use layouts to create a text representation of the information in a desired format. For example, Log4j includes an XMLLayout class that can be used to format LoggingEvents as strings of XML.

In Log4j, LoggingEvents are assigned a level that indicates their priority. The default levels in Log4j are (ordered from highest to lowest): OFF, FATAL, ERROR, WARN, INFO, DEBUG, and ALL. Loggers and appenders are also assigned a level, and will only execute logging requests that have a level that is equal to or greater than their own. For example, if an appender whose level is ERROR is asked to write out a LoggingEvent that has a level of WARN, the appender will not write out the given LogEvent.

All loggers in Log4j have a name. Log4j organizes logger instances in a tree structure according to their names the same way packages are organized in the Java language. As Log4j's documentation succinctly states: "A logger is said to be an ancestor of another logger if its name followed by a dot is a prefix of the descendant logger name. A logger is said to be a parent of a child logger if there are no ancestors between itself and the descendant logger." For example, a logger named "org.nrdc" is said to be the child of the "org" logger. The "org.nrdc.logging" logger is the child of the "org.nrdc" logger and the grandchild of the "org" logger. If a logger is not explicitly assigned a level, it uses the level of its closest ancestor that has been assigned a level. Loggers inherit appenders from their ancestors, although they can also be configured to use only appenders that are directly assigned to them.

When a logger is asked to log a message, it first checks that the level of the request is greater than or equal to its effective level. If so, it creates a LoggingEvent from the given message and passes the LoggingEvent to its appenders, which format it and send it to its output destinations.

Introduction to JUL
The java.util.logging package, which Sun introduced in 2002 with Java SDK version 1.4, came about as a result of JSR 47, Logging API Specification. JUL is extremely similar to Log4j - it more or less uses exactly the same concepts, but renames some of them. For example, appenders are "handlers," layouts are "formatters," and LoggingEvents are "LogRecords." Figure 1 summarizes Log4j and JUL names and concepts. JUL uses levels the same way that Log4J uses levels, although JUL has nine default levels instead of seven. JUL organizes loggers in a hierarchy the same way Log4j organizes its loggers, and JUL loggers inherit properties from their parent loggers in more or less the same way that Log4j loggers inherit properties from their parents. Concepts pretty much map one-to-one from Log4j to JUL; though the two libraries are different in subtle ways, any developer familiar with Log4j needs only to adjust his or her vocabulary to generally understand JUL.

Functionality Differences
While Log4j and JUL are almost conceptually identical, they do differ in terms of functionality. Their difference can be summarized as, "Whatever JUL can do, Log4j can also do - and more." They differ most in the areas of useful appender/handler implementations, useful formatter/layout implementations, and configuration flexibility.

JUL contains four concrete handler implementations, while Log4j includes over a dozen appender implementations. JUL's handlers are adequate for basic logging - they allow you to write to a buffer, to a console, to a socket, and to a file. Log4j's appenders, on the other hand, probably cover every logging output destination that you could think of. They can write to an NT event log or a Unix syslog, or even send e-mail. Figure 2 provides a summary of JUL's handlers and Log4j's appenders.

JUL contains two formatter classes: the XMLFormatter and SimpleFormatter. Log4j includes the corresponding layouts: the XMLLayout and SimpleLayout. Log4j also offers the TTCCLayout, which formats LoggingEvents into content-rich strings, and the HTMLLayout, which formats LoggingEvents as an HTML table.

While the TTCCLayout and HTMLLayout are useful, Log4j really pulls ahead of JUL in the formatter/handler arena because of the PatternLayout. PatternLayout instances can be configured with an enormous amount of flexibility via string conversion patterns, similar to the conversion patterns used by the printf function in C. In PatternLayout conversion patterns, special conversion characters are used to specify the information included in layout's formatted output. For example, "%t" is used to specify the name of the thread that started the logging of the message; "%C" is used to specify the name of the class of the object that started the logging of the message; and "%m" specifies the message. "%t: %m" would result in output such as "main thread: This is my message." "%C - %t: %m" would result in output such as "org.nrdc.My-Class - main thread: This is my message." The Pattern-Layout is extremely useful, and JUL's two formatter classes don't come anywhere near to matching its versatility. It's not uncommon for JUL users to write their own custom formatter class, whereas most Log4j users generally need to just learn how to use PatternLayout conversion patterns.

While both Log4j and JUL can be configured with configuration files, Log4j allows for a broader range of configuration possibilities through configuration files than JUL does. JUL can be configured with .properties files, but until J2SE 5.0 the configuration of handlers was only on a per-class rather than a per-instance basis. This means that if you are going to be using a pre-Tiger SDK, you'll miss out on useful configuration options, such as the ability to set up different FileHandler instances to send their output to different files.

It's important to note that pre-Tiger JUL can easily be configured to write to multiple output files in code, just not through its default configuration mechanism. Log4j can be configured with .properties and/or XML files, and appenders can be configured on a per-instance basis. Also, Log4j allows developers to associate layout instances with appender instances, and configure layouts on a per-instance basis. This includes PatternLayout instances - you can set the conversion pattern each uses in the configuration file. During development, it usually isn't a problem to recompile an application to adjust its logging configuration; after deployment, however, you may want to be able to tweak or even completely reconfigure your application's logging without recompiling. In that case, Log4j offers more flexibility, especially pre-Tiger.

More Stories By Joe McNamara

Joe McNamara is a software developer and logging guru at Quantum Leap Innovations, an innovator of intelligent software. At Quantum Leap Innovations, he works on a revolutionary multiagent system technology for the seamless and dynamic integration of wide numbers of applications, systems, and human users.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Bengt Rodehav 03/11/05 03:18:56 AM EST

I agree with the conclusion that log4j can do anything that JUL can do plus more. In my opinion, log4j is the "de facto" standard for logging in Java. When a "de facto" standard exists there is no need to creata a JSR to solve a problem since it has already been solved. JUL should never have been created.
However, since we now have two rivaling "standards" (log4j and JUL) there is a need for another API on top of them. This does already exist in Apache commons logging. The article lacks a discussion of when commons logging is appropriate. Assume, for example, that you are developing a product that will be used in many different organisations. Those organisations might have standardised what kind of logging to use. In those cases commons logging make sense. Otherwise I would stick to log4j.

@ThingsExpo Stories
Elon Musk is among the notable industry figures who worries about the power of AI to destroy rather than help society. Mark Zuckerberg, on the other hand, embraces all that is going on. AI is most powerful when deployed across the vast networks being built for Internets of Things in the manufacturing, transportation and logistics, retail, healthcare, government and other sectors. Is AI transforming IoT for the good or the bad? Do we need to worry about its potential destructive power? Or will we...
SYS-CON Events announced today that SIGMA Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. uLaser flow inspection device from the Japanese top share to Global Standard! Then, make the best use of data to flip to next page. For more information, visit http://www.sigma-k.co.jp/en/.
SYS-CON Events announced today that Daiya Industry will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Daiya Industry specializes in orthotic support systems and assistive devices with pneumatic artificial muscles in order to contribute to an extended healthy life expectancy. For more information, please visit https://www.daiyak...
SYS-CON Events announced today that B2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. B2Cloud specializes in IoT devices for preventive and predictive maintenance in any kind of equipment retrieving data like Energy consumption, working time, temperature, humidity, pressure, etc.
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp em...
SYS-CON Events announced today that Interface Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Interface Corporation is a company developing, manufacturing and marketing high quality and wide variety of industrial computers and interface modules such as PCIs and PCI express. For more information, visit http://www.i...
SYS-CON Events announced today that Mobile Create USA will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Mobile Create USA Inc. is an MVNO-based business model that uses portable communication devices and cellular-based infrastructure in the development, sales, operation and mobile communications systems incorporating GPS capabi...
SYS-CON Events announced today that Nihon Micron will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nihon Micron Co., Ltd. strives for technological innovation to establish high-density, high-precision processing technology for providing printed circuit board and metal mount RFID tags used for communication devices. For more inf...
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
SYS-CON Events announced today that Suzuki Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Suzuki Inc. is a semiconductor-related business, including sales of consuming parts, parts repair, and maintenance for semiconductor manufacturing machines, etc. It is also a health care business providing experimental research for...
While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 brings the mainstream adoption of containers for production workloads. In his session at 21st Cloud Expo, Ben McCormack, VP of Operations at Evernote, will discuss how data centers of the future will be managed, how th...
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that mruby Forum will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. mruby is the lightweight implementation of the Ruby language. We introduce mruby and the mruby IoT framework that enhances development productivity. For more information, visit http://forum.mruby.org/.
SYS-CON Events announced today that Fusic will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Fusic Co. provides mocks as virtual IoT devices. You can customize mocks, and get any amount of data at any time in your test. For more information, visit https://fusic.co.jp/english/.
In his session at @ThingsExpo, Greg Gorman is the Director, IoT Developer Ecosystem, Watson IoT, will provide a short tutorial on Node-RED, a Node.js-based programming tool for wiring together hardware devices, APIs and online services in new and interesting ways. It provides a browser-based editor that makes it easy to wire together flows using a wide range of nodes in the palette that can be deployed to its runtime in a single-click. There is a large library of contributed nodes that help so...
SYS-CON Events announced today that Enroute Lab will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enroute Lab is an industrial design, research and development company of unmanned robotic vehicle system. For more information, please visit http://elab.co.jp/.
Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
Real IoT production deployments running at scale are collecting sensor data from hundreds / thousands / millions of devices. The goal is to take business-critical actions on the real-time data and find insights from stored datasets. In his session at @ThingsExpo, John Walicki, Watson IoT Developer Advocate at IBM Cloud, will provide a fast-paced developer journey that follows the IoT sensor data from generation, to edge gateway, to edge analytics, to encryption, to the IBM Bluemix cloud, to Wa...