blob: 8f627fb342f17cd41f1d5efe81ce33595b5e5102 [file] [log] [blame]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Generated by Apache Maven Doxia at May 13, 2012 -->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Apache log4j 1.2 -
Short introduction to log4j</title>
<style type="text/css" media="all">
@import url("./css/maven-base.css");
@import url("./css/maven-theme.css");
@import url("./css/site.css");
</style>
<link rel="stylesheet" href="./css/print.css" type="text/css" media="print" />
<meta name="author" content="Ceki Gülcü" />
<meta name="Date-Revision-yyyymmdd" content="20120513" />
<meta http-equiv="Content-Language" content="en" />
</head>
<body class="composite">
<div id="banner">
<a href="../../" id="bannerLeft">
<img src="images/ls-logo.jpg" alt="Apache Logging Services Project" />
</a>
<a href=".." id="bannerRight">
<img src="images/logo.jpg" alt="Apache log4j™" />
</a>
<div class="clear">
<hr/>
</div>
</div>
<div id="breadcrumbs">
<div class="xleft">
<span id="publishDate">Last Published: 2012-05-13</span>
&nbsp;| <span id="projectVersion">Version: 1.2.17</span>
| <a href="http://www.apache.org/" class="externalLink" title="Apache">Apache</a>
&gt;
<a href="../../" title="Logging Services">Logging Services</a>
&gt;
<a href="../" title="log4j">log4j</a>
&gt;
<a href="./" title="1.2">1.2</a>
</div>
<div class="xright">
</div>
<div class="clear">
<hr/>
</div>
</div>
<div id="leftColumn">
<div id="navcolumn">
<h5>About log4j 1.2</h5>
<ul>
<li class="none">
<a href="index.html" title="What is log4j?">What is log4j?</a>
</li>
<li class="none">
<a href="download.html" title="Download">Download</a>
</li>
<li class="none">
<a href="faq.html" title="FAQ">FAQ</a>
</li>
<li class="none">
<a href="roadmap.html" title="Roadmap">Roadmap</a>
</li>
</ul>
<h5>Community</h5>
<ul>
<li class="none">
<a href="mail-lists.html" title="Mailing Lists">Mailing Lists</a>
</li>
<li class="none">
<a href="issue-tracking.html" title="Issue Tracking">Issue Tracking</a>
</li>
<li class="none">
<a href="http://blogs.apache.org/logging/" class="externalLink" title="Blog">Blog</a>
</li>
</ul>
<h5>Documentation</h5>
<ul>
<li class="none">
<strong>Introduction</strong>
</li>
<li class="none">
<a href="apidocs/index.html" title="JavaDoc">JavaDoc</a>
</li>
<li class="none">
<a href="publications.html" title="Publications">Publications</a>
</li>
<li class="none">
<a href="building.html" title="Building">Building</a>
</li>
<li class="none">
<a href="http://wiki.apache.org/logging-log4j" class="externalLink" title="Wiki">Wiki</a>
</li>
</ul>
<h5>Project Documentation</h5>
<ul>
<li class="collapsed">
<a href="project-info.html" title="Project Information">Project Information</a>
</li>
<li class="collapsed">
<a href="project-reports.html" title="Project Reports">Project Reports</a>
</li>
</ul>
<h5>Apache</h5>
<ul>
<li class="none">
<a href="http://www.apache.org" class="externalLink" title="Home">Home</a>
</li>
<li class="none">
<a href="http://www.apache.org/licenses" class="externalLink" title="License">License</a>
</li>
<li class="none">
<a href="http://www.apache.org/foundation/sponsorship.html" class="externalLink" title="Sponsorship">Sponsorship</a>
</li>
<li class="none">
<a href="http://www.apache.org/foundation/thanks.html" class="externalLink" title="Thanks">Thanks</a>
</li>
<li class="none">
<a href="http://www.apache.org/security/" class="externalLink" title="Security">Security</a>
</li>
<li class="none">
<a href="http://www.apachecon.com" class="externalLink" title="Conferences">Conferences</a>
</li>
</ul>
<a href="http://maven.apache.org/" title="Built by Maven" class="poweredBy">
<img class="poweredBy" alt="Built by Maven" src="./images/maven-feather.png" />
</a>
</div>
</div>
<div id="bodyColumn">
<div id="contentBox">
<!-- Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. -->
<div align="center">
<br><br>
<a href="https://jaxlondon.com/jax-awards/"><img src="images/VoteLog4j2-JAX2016InnovationAward.jpg"></a>
<p>
<table border="1" cellspacing="0" align="center" style="width:400px">
<tr>
<td align="center">
Log4j 2 is nominated for the JAX Innovation Awards! <br><br>
Do you like its performance, garbage-free logging, and easy and flexible configuration?<br><br>
Log4j 2 needs your love.
<a href="https://jaxlondon.com/jax-awards/">Vote for Log4j 2!</a><br><br>
</td>
</tr>
</table>
</div>
<div class="section"><h2>End of Life</h2>
<p>On August 5, 2015 the Logging Services Project Management Committee announced that Log4j 1.x had reached end of life.
For complete text of the announcement please see the
<a href="http://blogs.apache.org/foundation/entry/apache_logging_services_project_announces">Apache Blog</a>.
Users of Log4j 1 are recommended to upgrade to <a class="externalLink" href="http://logging.apache.org/log4j/2.x/index.html">Apache Log4j 2</a>.</p>
</div>
<div class="section"><h2>Short introduction to log4j: Ceki G&#xfc;lc&#xfc;, March 2002<a name="Short_introduction_to_log4j:_Ceki_Glc_March_2002"></a></h2>
<p>
Copyright &#xa9; 2000-2002 The Apache Software Foundation. All
rights reserved. This software is published under the terms of
the Apache Software License version 2.0, a copy of which has
been included in the LICENSE file shipped with the log4j
distribution. This document is based on the article <a class="externalLink" href="http://www.javaworld.com/jw-11-2000/jw-1122-log4j.html">&quot;Log4j
delivers control over logging&quot;</a> published in November 2000
edition of JavaWorld. However, the present article contains more
detailed and up to date information. The present short manual
also borrows some text from <a class="externalLink" href="https://www.qos.ch/shop/products/eclm/">&quot;<i>The
complete log4j manual</i>&quot;</a> by the same author (yours
truly).</p>
<div class="section"><h2>Abstract<a name="Abstract"></a></h2>
<p>This document describes the log4j API, its unique features and
design rationale. Log4j is an open source project based on the work of
many authors. It allows the developer to control which log statements
are output with arbitrary granularity. It is fully configurable at
runtime using external configuration files. Best of all, log4j has a
gentle learning curve. Beware: judging from user feedback, it is also
quite addictive.</p>
<div class="section"><h2>Introduction<a name="Introduction"></a></h2>
<p>Almost every large application includes its own logging or tracing
API. In conformance with this rule, the E.U. <a class="externalLink" href="http://www.semper.org">SEMPER</a> project decided to write its
own tracing API. This was in early 1996. After countless enhancements,
several incarnations and much work that API has evolved to become
log4j, a popular logging package for Java. The package is distributed
under the <a href="license.html">Apache Software License</a>, a
fully-fledged open source license certified by the <a class="externalLink" href="http://www.opensource.org">open source</a> initiative. The
latest log4j version, including full-source code, class files and
documentation can be found at <a class="externalLink" href="http://logging.apache.org/log4j/"><b>http://logging.apache.org/log4j/</b></a>.
By the way, log4j has been ported to the C, C++, C#, Perl, Python,
Ruby, and Eiffel languages.</p>
<p>Inserting log statements into code is a low-tech method for
debugging it. It may also be the only way because debuggers are not
always available or applicable. This is usually the case for
multithreaded applications and distributed applications at large.</p>
<p>Experience indicates that logging was an important component of the
development cycle. It offers several advantages. It provides precise
<i>context</i> about a run of the application. Once inserted into
the code, the generation of logging output requires no human
intervention. Moreover, log output can be saved in persistent medium
to be studied at a later time. In addition to its use in the
development cycle, a sufficiently rich logging package can also be
viewed as an auditing tool.</p>
<p>As Brian W. Kernighan and Rob Pike put it in their truly excellent
book <i>&quot;The Practice of Programming&quot;</i>
</p><div><pre>
As personal choice, we tend not to use debuggers beyond getting a
stack trace or the value of a variable or two. One reason is that it
is easy to get lost in details of complicated data structures and
control flow; we find stepping through a program less productive
than thinking harder and adding output statements and self-checking
code at critical places. Clicking over statements takes longer than
scanning the output of judiciously-placed displays. It takes less
time to decide where to put print statements than to single-step to
the critical section of code, even assuming we know where that
is. More important, debugging statements stay with the program;
debugging sessions are transient.
</pre></div>
<p>Logging does have its drawbacks. It can slow down an
application. If too verbose, it can cause scrolling blindness. To
alleviate these concerns, log4j is designed to be reliable, fast and
extensible. Since logging is rarely the main focus of an application,
the log4j API strives to be simple to understand and to use.</p>
<div class="section"><h2>Loggers, Appenders and Layouts<a name="Loggers_Appenders_and_Layouts"></a></h2>
<p>Log4j has three main components: <i>loggers</i>,
<i>appenders</i> and <i>layouts</i>. These three types of
components work together to enable developers to log messages according
to message type and level, and to control at runtime how these
messages are formatted and where they are reported.</p>
<div class="section"><h3>Logger hierarchy<a name="Logger_hierarchy"></a></h3>
<p>The first and foremost advantage of any logging API over plain
<tt>System.out.println</tt> resides in its ability to disable
certain log statements while allowing others to print unhindered. This
capability assumes that the logging space, that is, the space of all
possible logging statements, is categorized according to some
developer-chosen criteria. This observation had previously led us to
choose <i>category</i> as the central concept of the
package. However, since log4j version 1.2, <tt>Logger</tt> class
has replaced the <tt>Category</tt> class. For those familiar with
earlier versions of log4j, the <tt>Logger</tt> class can be
considered as a mere alias to the <tt>Category</tt> class.</p>
<p>Loggers are named entities. Logger names are case-sensitive and
they follow the hierarchical naming rule:</p>
<p>
</p><table border="0" class="bodyTable" bgcolor="#EEEE99">
<tr class="a">
<td>
<dl>
<dt><b>Named Hierarchy</b></dt>
<dd>A logger is said to be an <i>ancestor</i> of another
logger if its name followed by a dot is a prefix of the
<i>descendant</i> logger name. A logger is said to be a
<i>parent</i> of a <i>child</i> logger if there are no
ancestors between itself and the descendant logger.</dd>
</dl>
</td></tr></table>
<p>For example, the logger named <tt>&quot;com.foo&quot;</tt> is a parent
of the logger named <tt>&quot;com.foo.Bar&quot;</tt>. Similarly,
<tt>&quot;java&quot;</tt> is a parent of <tt>&quot;java.util&quot;</tt> and an
ancestor of <tt>&quot;java.util.Vector&quot;</tt>. This naming scheme
should be familiar to most developers.</p>
<p>The root logger resides at the top of the logger hierarchy. It
is exceptional in two ways:
</p><ol style="list-style-type: decimal">
<li> it always exists,</li>
<li> it cannot be retrieved by name.</li>
</ol>
<p>Invoking the class static <a href="apidocs/org/apache/log4j/Logger.html#getRootLogger">Logger.getRootLogger</a>
method retrieves it. All other loggers are instantiated and
retrieved with the class static <a href="apidocs/org/apache/log4j/Logger.html#getLoggerjava.lang.String">Logger.getLogger</a>
method. This method takes the name of the desired logger as a
parameter. Some of the basic methods in the Logger class are listed
below.</p>
<p></p><table border="0" class="bodyTable">
<tr class="a" bgcolor="CCCCCC">
<td>
<div><pre>
package org.apache.log4j;
public class <b>Logger</b> {
// Creation &amp; retrieval methods:
public static Logger getRootLogger();
public static Logger getLogger(String name);
// printing methods:
public void trace(Object message);
public void debug(Object message);
public void info(Object message);
public void warn(Object message);
public void error(Object message);
public void fatal(Object message);
// generic printing method:
public void log(Level l, Object message);
}
</pre></div>
</td>
</tr>
</table>
<p>Loggers <i>may</i> be assigned levels. The set of possible
levels, that is:<br /><br />
<a href="apidocs/org/apache/log4j/Level.html#TRACE">TRACE</a>,<br />
<a href="apidocs/org/apache/log4j/Level.html#DEBUG">DEBUG</a>,<br />
<a href="apidocs/org/apache/log4j/Level.html#INFO">INFO</a>,<br />
<a href="apidocs/org/apache/log4j/Level.html#WARN">WARN</a>,<br />
<a href="apidocs/org/apache/log4j/Level.html#ERROR">ERROR</a> and<br />
<a href="apidocs/org/apache/log4j/Level.html#FATAL">FATAL</a><br />
<br />
are defined in the <tt><a href="apidocs/org/apache/log4j/Level.html">org.apache.log4j.Level</a></tt>
class. Although we do not encourage you to do so, you may define
your own levels by sub-classing the <tt>Level</tt> class. A
perhaps better approach will be explained later on.</p>
<p>If a given logger is not assigned a level, then it inherits
one from its closest ancestor with an assigned level. More
formally:</p>
<p>
</p><table border="0" class="bodyTable" bgcolor="#EEEE99">
<tr class="a">
<td>
<dl>
<dt><b>Level Inheritance</b></dt>
<dd><p>The <i>inherited level</i> for a given logger
<i>C</i>, is equal to the first non-null level in the logger
hierarchy, starting at <i>C</i> and proceeding upwards in the
hierarchy towards the <tt>root</tt> logger.</p></dd>
</dl>
</td>
</tr>
</table>
<p>To ensure that all loggers can eventually inherit a level,
the root logger always has an assigned level.</p>
<p>Below are four tables with various assigned level values and the
resulting inherited levels according to the above rule.</p>
<p>
</p><caption align="bottom">Example 1</caption><table class="bodyTable" border="1">
<tr class="a"><th>Logger<br />name</th><th>Assigned<br />level</th>
<th>Inherited<br />level</th></tr>
<tr class="b" align="left"><td>root</td> <td>Proot</td> <td>Proot</td></tr>
<tr class="a" align="left"><td>X </td> <td>none</td> <td>Proot</td></tr>
<tr class="b" align="left"><td>X.Y </td> <td>none</td> <td>Proot</td></tr>
<tr class="a" align="left"><td>X.Y.Z</td> <td>none</td> <td>Proot</td></tr>
</table>
<p>In example 1 above, only the root logger is assigned a
level. This level value, <tt>Proot</tt>, is inherited by the
other loggers <tt>X</tt>, <tt>X.Y</tt> and
<tt>X.Y.Z</tt>.</p>
<p>
</p><caption align="bottom">Example 2</caption><table class="bodyTable" border="1">
<tr class="a"><th>Logger<br />name</th><th>Assigned<br />level</th>
<th>Inherited<br />level</th></tr>
<tr class="b" align="left"><td>root</td> <td>Proot</td> <td>Proot</td></tr>
<tr class="a" align="left"><td>X </td> <td>Px</td> <td>Px</td></tr>
<tr class="b" align="left"><td>X.Y </td> <td>Pxy</td> <td>Pxy</td></tr>
<tr class="a" align="left"><td>X.Y.Z</td> <td>Pxyz</td> <td>Pxyz</td></tr>
</table>
<p>In example 2, all loggers have an assigned level value. There
is no need for level inheritence.</p>
<p></p><caption align="bottom">Example 3</caption><table class="bodyTable" border="1">
<tr class="a"><th>Logger<br />name</th><th>Assigned<br />level</th>
<th>Inherited<br />level</th></tr>
<tr class="b" align="left"><td>root</td> <td>Proot</td> <td>Proot</td></tr>
<tr class="a" align="left"><td>X </td> <td>Px</td> <td>Px</td></tr>
<tr class="b" align="left"><td>X.Y </td> <td>none</td> <td>Px</td></tr>
<tr class="a" align="left"><td>X.Y.Z</td> <td>Pxyz</td> <td>Pxyz</td></tr>
</table>
<p>In example 3, the loggers <tt>root</tt>, <tt>X</tt> and
<tt>X.Y.Z</tt> are assigned the levels <tt>Proot</tt>,
<tt>Px</tt> and <tt>Pxyz</tt> respectively. The logger
<tt>X.Y</tt> inherits its level value from its parent
<tt>X</tt>.</p>
<table class="bodyTable" border="1"><caption align="bottom">Example 4</caption>
<tr class="a"><th>Logger<br />name</th><th>Assigned<br />level</th>
<th>Inherited<br />level</th></tr>
<tr class="b" align="left"><td>root</td> <td>Proot</td> <td>Proot</td></tr>
<tr class="a" align="left"><td>X </td> <td>Px</td> <td>Px</td></tr>
<tr class="b" align="left"><td>X.Y </td> <td>none</td> <td>Px</td></tr>
<tr class="a" align="left"><td>X.Y.Z</td> <td>none</td> <td>Px</td></tr>
</table>
<p>In example 4, the loggers <tt>root</tt> and <tt>X</tt>
and are assigned the levels <tt>Proot</tt> and <tt>Px</tt>
respectively. The loggers <tt>X.Y</tt> and <tt>X.Y.Z</tt>
inherits their level value from their nearest parent <tt>X</tt>
having an assigned level..</p>
<p>Logging requests are made by invoking one of the printing methods
of a logger instance. These printing methods are
<tt>
<a href="apidocs/org/apache/log4j/Category.html#debugjava.lang.Object">debug</a>,
<a href="apidocs/org/apache/log4j/Category.html#infojava.lang.Object">info</a>,
<a href="apidocs/org/apache/log4j/Category.html#warnjava.lang.Object">warn</a>,
<a href="apidocs/org/apache/log4j//Category.html#errorjava.lang.Object">error</a>,
<a href="apidocs/org/apache/log4j/Category.html#fataljava.lang.Object">fatal</a>
and <a href="apidocs/org/apache/log4j/Category.html#logorg.apache.log4j.Priority_java.lang.Object">log</a></tt>.</p>
<p>By definition, the printing method determines the level of a
logging request. For example, if <tt>c</tt> is a logger
instance, then the statement <tt>c.info(&quot;..&quot;)</tt> is a logging
request of level INFO.</p>
<p>A logging request is said to be <i>enabled</i> if its level is
higher than or equal to the level of its logger. Otherwise, the
request is said to be <i>disabled</i>. A logger without an
assigned level will inherit one from the hierarchy. This rule is
summarized below.</p>
<p>
<a name="selectionRule"></a></p><table border="0" class="bodyTable" bgcolor="#EEEE99">
<tr class="a">
<td>
<dl>
<dt><b>Basic Selection Rule</b></dt>
<dd><p>A log request of level <i>p</i> in a logger with
(either assigned or inherited, whichever is appropriate) level <i>q</i>, is enabled if <i> p &gt;=
q</i>.</p></dd>
</dl>
</td></tr></table>
<p>This rule is at the heart of log4j. It assumes that levels are
ordered. For the standard levels, we have <tt>DEBUG &lt; INFO
&lt; WARN &lt; ERROR &lt; FATAL</tt>.</p>
<p>Here is an example of this rule.</p>
<p></p><table border="0" class="bodyTable" bgcolor="CCCCCC">
<tr class="a"><td>
<div><pre>
// get a logger instance named &quot;com.foo&quot;
Logger logger = Logger.getLogger(<b>&quot;com.foo&quot;</b>);
// Now set its level. Normally you do not need to set the
// level of a logger programmatically. This is usually done
// in configuration files.
<b>logger</b>.setLevel(<font color="0000AA"><b>Level.INFO</b></font>);
Logger barlogger = Logger.getLogger(<b>&quot;com.foo.Bar&quot;</b>);
// This request is enabled, because <font color="00AA00"><b>WARN</b></font> &gt;= <font color="0000AA"><b>INFO</b></font>.
logger.<font color="00AA00"><b>warn</b></font>(&quot;Low fuel level.&quot;);
// This request is disabled, because <font color="00AA00"><b>DEBUG</b></font> &lt; <font color="0000AA"><b>INFO</b></font>.
logger.<font color="00AA00"><b>debug</b></font>(&quot;Starting search for nearest gas station.&quot;);
// The logger instance barlogger, named &quot;com.foo.Bar&quot;,
// will inherit its level from the logger named
// &quot;com.foo&quot; Thus, the following request is enabled
// because <font color="00AA00"><b>INFO</b></font> &gt;= <font color="0000AA"><b>INFO</b></font>.
barlogger.<font color="00AA00"><b>info</b></font>(&quot;Located nearest gas station.&quot;);
// This request is disabled, because <font color="00AA00"><b>DEBUG</b></font> &lt; <font color="0000AA"><b>INFO</b></font>.
barlogger.<font color="00AA00"><b>debug</b></font>(&quot;Exiting gas station search&quot;);
</pre></div>
</td></tr>
</table>
<p>Calling the <tt>getLogger</tt> method with the same name will
always return a reference to the exact same logger object.</p>
<p>For example, in
</p><table border="0" class="bodyTable" bgcolor="CCCCCC">
<tr class="a"><td>
<div><pre>
Logger x = Logger.getLogger(&quot;wombat&quot;);
Logger y = Logger.getLogger(&quot;wombat&quot;);</pre></div>
</td></tr>
</table>
<tt>x</tt> and <tt>y</tt> refer to <i>exactly</i> the same
logger object.
<p>Thus, it is possible to configure a logger and then to retrieve
the same instance somewhere else in the code without passing around
references. In fundamental contradiction to biological parenthood,
where parents always preceed their children, log4j loggers can be
created and configured in any order. In particular, a &quot;parent&quot;
logger will find and link to its descendants even if it is
instantiated after them.</p>
<p>Configuration of the log4j environment is typically done at
application initialization. The preferred way is by reading a
configuration file. This approach will be discussed shortly.</p>
<p>Log4j makes it easy to name loggers by <i>software
component</i>. This can be accomplished by statically instantiating
a logger in each class, with the logger name equal to the fully
qualified name of the class. This is a useful and straightforward
method of defining loggers. As the log output bears the name of the
generating logger, this naming strategy makes it easy to identify
the origin of a log message. However, this is only one possible,
albeit common, strategy for naming loggers. Log4j does not restrict
the possible set of loggers. The developer is free to name the
loggers as desired.</p>
<p>Nevertheless, naming loggers after the class where they are
located seems to be the best strategy known so far.</p>
</div><div class="section"><h2>Appenders and Layouts<a name="Appenders_and_Layouts"></a></h2>
<p>The ability to selectively enable or disable logging requests based
on their logger is only part of the picture. Log4j allows logging
requests to print to multiple destinations. In log4j speak, an output
destination is called an <i>appender</i>. Currently, appenders exist
for the <a href="apidocs/org/apache/log4j/ConsoleAppender.html">console</a>, <a href="apidocs/org/apache/log4j/FileAppender.html">files</a>, GUI
components, <a href="apidocs/org/apache/log4j/net/SocketAppender.html">remote socket</a>
servers, <a href="apidocs/org/apache/log4j/net/JMSAppender.html">JMS</a>,
<a href="apidocs/org/apache/log4j/nt/NTEventLogAppender.html"> NT
Event Loggers</a>, and remote UNIX <a href="apidocs/org/apache/log4j/net/SyslogAppender.html">Syslog</a>
daemons. It is also possible to log <a href="apidocs/org/apache/log4j/AsyncAppender.html">asynchronously</a>.</p>
<p>More than one appender can be attached to a logger.</p>
<p>The <a href="apidocs/org/apache/log4j/Category.html#addAppenderorg.apache.log4j.Appender">addAppender</a>
method adds an appender to a given logger.
<b>Each enabled logging
request for a given logger will be forwarded to all the appenders in
that logger as well as the appenders higher in the hierarchy.</b> In
other words, appenders are inherited additively from the logger
hierarchy. For example, if a console appender is added to the root
logger, then all enabled logging requests will at least print on the
console. If in addition a file appender is added to a logger, say
<i>C</i>, then enabled logging requests for <i>C</i> and
<i>C</i>'s children will print on a file <i>and</i> on the
console. It is possible to override this default behavior so that
appender accumulation is no longer additive by <a href="apidocs/org/apache/log4j/Category.html#setAdditivityboolean">setting
the additivity flag</a> to <tt>false</tt>.</p>
<p>The rules governing appender additivity are summarized below.</p>
<p>
<a name="additivity"></a></p><table border="0" class="bodyTable" bgcolor="#EEEE99">
<tr class="a">
<td>
<dl>
<dt><b>Appender Additivity</b></dt>
<dd><p>The output of a log statement of logger <i>C</i> will
go to all the appenders in <i>C</i> and its ancestors. This is
the meaning of the term &quot;appender additivity&quot;.</p>
<p>However, if an ancestor of logger <i>C</i>, say <i>P</i>,
has the additivity flag set to <tt>false</tt>, then
<i>C</i>'s output will be directed to all the appenders in
<i>C</i> and its ancestors upto and including <i>P</i> but
not the appenders in any of the ancestors of <i>P</i>.</p>
<p>Loggers have their additivity flag set to
<tt>true</tt> by default.</p></dd>
</dl></td></tr>
</table>
<p>The table below shows an example:</p>
<p></p><table class="bodyTable" align="center" border="3" cellpadding="10">
<tr class="a">
<th>Logger<br />Name </th><th>Added<br />Appenders</th> <th>Additivity<br />Flag</th> <th>Output Targets</th> <th>Comment</th>
</tr>
<tr class="b"><td>root </td><td>A1 </td><td>not applicable </td><td>A1</td>
<td>The root logger is anonymous but can be accessed with the
Logger.getRootLogger() method. There is no default appender
attached to root.</td></tr>
<tr class="a"><td>x </td><td>A-x1, A-x2 </td><td>true </td><td>A1, A-x1, A-x2</td>
<td>Appenders of &quot;x&quot; and root.</td></tr>
<tr class="b"><td>x.y </td><td>none </td><td>true </td><td>A1, A-x1, A-x2</td>
<td>Appenders of &quot;x&quot; and root.</td></tr>
<tr class="a"><td>x.y.z </td><td>A-xyz1 </td><td>true </td><td>A1, A-x1, A-x2, A-xyz1</td>
<td>Appenders in &quot;x.y.z&quot;, &quot;x&quot; and root.</td></tr>
<tr class="b"><td>security </td><td>A-sec </td><td><font color="blue">false</font></td>
<td>A-sec</td>
<td>No appender accumulation since the additivity flag is set to
<tt>false</tt>.</td></tr>
<tr class="a"><td>security.access </td><td>none </td><td> true </td><td> A-sec </td><td>Only
appenders of &quot;security&quot; because the additivity flag in &quot;security&quot; is
set to <tt>false</tt>.</td></tr>
</table>
<p>More often than not, users wish to customize not only the output
destination but also the output format. This is accomplished by
associating a <i>layout</i> with an appender. The layout is
responsible for formatting the logging request according to the user's
wishes, whereas an appender takes care of sending the formatted output
to its destination.</p>
The <a href="apidocs/org/apache/log4j/PatternLayout.html">PatternLayout</a>, part
of the standard log4j distribution, lets the user specify the output
format according to conversion patterns similar to the C language
<tt>printf</tt> function.
<p>For example, the PatternLayout with the conversion pattern &quot;%r [%t]
%-5p %c - %m%n&quot; will output something akin to:<br />
</p><div><pre>
176 [main] INFO org.foo.Bar - Located nearest gas station.
</pre></div>
<p>The first field is the number of milliseconds elapsed since the
start of the program. The second field is the thread making the log
request. The third field is the level of the log statement. The
fourth field is the name of the logger associated with the log
request. The text after the '-' is the message of the statement.</p>
<p>Just as importantly, log4j will render the content of the log
message according to user specified criteria. For example, if you
frequently need to log <tt>Oranges</tt>, an object type used in
your current project, then you can register an
<tt>OrangeRenderer</tt> that will be invoked whenever an orange
needs to be logged.</p>
<p>Object rendering follows the class hierarchy. For example, assuming
oranges are fruits, if you register a <tt>FruitRenderer</tt>, all
fruits including oranges will be rendered by the
<tt>FruitRenderer</tt>, unless of course you registered an orange
specific <tt>OrangeRenderer</tt>.</p>
<p>Object renderers have to implement the
<a href="apidocs/org/apache/log4j/or/ObjectRenderer.html">ObjectRenderer</a>
interface.</p>
<div class="section"><h2>Configuration<a name="Configuration"></a></h2>
<p>Inserting log requests into the application code requires a fair
amount of planning and effort. Observation shows that approximately 4
percent of code is dedicated to logging. Consequently, even moderately
sized applications will have thousands of logging statements embedded
within their code. Given their number, it becomes imperative to
manage these log statements without the need to modify them manually.</p>
<p>The log4j environment is fully configurable programmatically.
However, it is far more flexible to configure log4j using
configuration files. Currently, configuration files can be written in
XML or in Java properties (key=value) format.</p>
<p>Let us give a taste of how this is done with the help of an
imaginary application <tt>MyApp</tt> that uses log4j.</p>
<p></p><table border="0" class="bodyTable" bgcolor="CCCCCC"><tr class="a"><td>
<div><pre>
import com.foo.Bar;
// Import log4j classes.
<b>import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;</b>
public class MyApp {
// Define a static logger variable so that it references the
// Logger instance named &quot;MyApp&quot;.
<b>static</b> Logger logger = <b>Logger.getLogger(MyApp.class);</b>
public static void main(String[] args) {
// Set up a simple configuration that logs on the console.
<b>BasicConfigurator.configure();</b>
logger.info(&quot;Entering application.&quot;);
Bar bar = new Bar();
bar.doIt();
logger.info(&quot;Exiting application.&quot;);
}
}
</pre></div>
</td></tr>
</table>
<p><tt>MyApp</tt> begins by importing log4j related classes. It
then defines a static logger variable with the name
<tt>MyApp</tt> which happens to be the fully qualified name of the
class.</p>
<p><tt>MyApp</tt> uses the <tt>Bar</tt> class defined in the
package <tt>com.foo</tt>.</p>
<p></p><table border="0" class="bodyTable" bgcolor="CCCCCC"><tr class="a"><td>
<div><pre>
<b>package com.foo;</b>
import org.apache.log4j.Logger;
public class Bar {
<b>static</b> Logger logger = <b>Logger.getLogger(Bar.class);</b>
public void doIt() {
logger.debug(&quot;Did it again!&quot;);
}
}
</pre></div>
</td></tr>
</table>
<p>The invocation of the <a href="apidocs/org/apache/log4j/BasicConfigurator.html#configure">BasicConfigurator.configure</a>
method creates a rather simple log4j setup. This method is hardwired
to add to the root logger a <a href="apidocs/org/apache/log4j/ConsoleAppender.html">
ConsoleAppender</a>. The output will be formatted using a <a href="apidocs/org/apache/log4j/PatternLayout.html">PatternLayout</a> set
to the pattern &quot;%-4r [%t] %-5p %c %x - %m%n&quot;.</p>
<p>Note that by default, the root logger is assigned to
<tt>Level.DEBUG</tt>.</p>
<p>The output of MyApp is:
</p><div><pre>
0 [main] INFO MyApp - Entering application.
36 [main] DEBUG com.foo.Bar - Did it again!
51 [main] INFO MyApp - Exiting application.
</pre></div>
<p>The figure below depicts the object diagram of <tt>MyApp</tt>
after just having called the <tt>BasicConfigurator.configure</tt>
method.</p>
<p>
<center>
<img src="images/od.gif" align="center" alt="" />
</center></p>
<p>As a side note, let me mention that in log4j child loggers link
only to their existing ancestors. In particular, the logger named
<tt>com.foo.Bar</tt> is linked directly to the <tt>root</tt>
logger, thereby circumventing the unused <tt>com</tt> or
<tt>com.foo</tt> loggers. This significantly increases
performance and reduces log4j's memory footprint.</p>
<p>The <tt>MyApp</tt> class configures log4j by invoking
<tt>BasicConfigurator.configure</tt> method. Other classes only
need to import the <tt>org.apache.log4j.Logger</tt> class,
retrieve the loggers they wish to use, and log away.</p>
<p>The previous example always outputs the same log information.
Fortunately, it is easy to modify <tt>MyApp</tt> so that the log
output can be controlled at run-time. Here is a slightly modified
version.</p>
<p></p><table border="0" class="bodyTable" bgcolor="CCCCCC"><tr class="a"><td>
<div><pre>
import com.foo.Bar;
import org.apache.log4j.Logger;
<b>import org.apache.log4j.PropertyConfigurator;</b>
public class MyApp {
static Logger logger = Logger.getLogger(MyApp.class.getName());
public static void main(String[] args) {
// BasicConfigurator replaced with PropertyConfigurator.
<b>PropertyConfigurator.configure(args[0]);</b>
logger.info(&quot;Entering application.&quot;);
Bar bar = new Bar();
bar.doIt();
logger.info(&quot;Exiting application.&quot;);
}
}
</pre></div>
</td></tr>
</table>
<p>This version of <tt>MyApp</tt> instructs
<tt>PropertyConfigurator</tt> to parse a configuration file and
set up logging accordingly.</p>
<p>Here is a sample configuration file that results in identical
output as the previous <tt>BasicConfigurator</tt> based example.</p>
<p></p><table border="0" class="bodyTable" bgcolor="CCAAAA"><tr class="a"><td>
<div><pre>
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
</pre></div>
</td></tr></table>
<!-- <p>Please note that if you copy and paste the examples, then result is
likely to include trailing spaces on some lines. These trailing spaces
are not trimmed out but interpreted by the PropertyConfigurator. By
the time you read this article the problem should be corrected. -->
<p>Suppose we are no longer interested in seeing the output of any
component belonging to the <tt>com.foo</tt> package. The following
configuration file shows one possible way of achieving this.</p>
<p></p><table border="0" class="bodyTable" bgcolor="CCAAAA"><tr class="a"><td>
<div><pre>
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
# <b>Print the date in ISO 8601 format</b>
log4j.appender.A1.layout.ConversionPattern=<b>%d</b> [%t] %-5p %c - %m%n
# Print only messages of level WARN or above in the package com.foo.
<b>log4j.logger.com.foo=WARN</b>
</pre></div>
</td></tr></table>
<p>The output of <tt>MyApp</tt> configured with this file is shown below.</p>
<div><pre>
<b>2000-09-07 14:07:41,508</b> [main] INFO MyApp - Entering application.
<b>2000-09-07 14:07:41,529</b> [main] INFO MyApp - Exiting application.
</pre></div>
<p>As the logger <tt>com.foo.Bar</tt> does not have an assigned
level, it inherits its level from <tt>com.foo</tt>, which
was set to WARN in the configuration file. The log statement from the
<tt>Bar.doIt</tt> method has the level DEBUG, lower than the
logger level WARN. Consequently, <tt>doIt()</tt> method's log
request is suppressed.</p>
<p>Here is another configuration file that uses multiple appenders.</p>
<p></p><table border="0" class="bodyTable" bgcolor="CCAAAA"><tr class="a"><td>
<div><pre>
log4j.rootLogger=debug, <b>stdout, R</b>
log4j.appender.<b>stdout</b>=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] <b>(%F:%L)</b> - %m%n
log4j.appender.<b>R</b>=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=<b>100KB</b>
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
</pre></div>
</td></tr></table>
<p>Calling the enhanced MyApp with the this configuration file will
output the following on the console.</p>
<div><pre>
INFO [main] <b>(MyApp2.java:12)</b> - Entering application.
DEBUG [main] (Bar.java:8) - Doing it again!
INFO [main] (MyApp2.java:15) - Exiting application.
</pre></div>
<p>In addition, as the root logger has been allocated a second
appender, output will also be directed to the <tt>example.log</tt>
file. This file will be rolled over when it reaches 100KB. When
roll-over occurs, the old version of <tt>example.log</tt> is
automatically moved to <tt>example.log.1</tt>.</p>
<p>Note that to obtain these different logging behaviors we did not
need to recompile code. We could just as easily have logged to a UNIX
Syslog daemon, redirected all <tt>com.foo</tt> output to an NT
Event logger, or forwarded logging events to a remote log4j server,
which would log according to local server policy, for example by
forwarding the log event to a second log4j server.</p>
<a name="defaultInit"></a><div class="section"><h2>Default Initialization Procedure<a name="Default_Initialization_Procedure"></a></h2>
<p>The log4j library does not make any assumptions about its
environment. In particular, there are no default log4j
appenders. Under certain well-defined circumstances however, the
static inializer of the <tt>Logger</tt> class will attempt to
automatically configure log4j. The Java language guarantees that the
static initializer of a class is called once and only once during the
loading of a class into memory. It is important to remember that
different classloaders may load distinct copies of the same
class. These copies of the same class are considered as totally
unrelated by the JVM.</p>
<p>The default initialization is very useful in environments where the
exact entry point to the application depends on the runtime
environment. For example, the same application can be used as a
stand-alone application, as an applet, or as a servlet under the
control of a web-server.</p>
<p>The exact default initialization algorithm is defined as follows:</p>
<ol style="list-style-type: decimal">
<li>Setting the <b>log4j.defaultInitOverride</b> system property to
any other value then &quot;false&quot; will cause log4j to skip the default
initialization procedure (this procedure).</li>
<li>Set the <tt>resource</tt> string variable to the value of
the <b>log4j.configuration</b> system property. <i>The preferred
way to specify the default initialization file is through the
<b>log4j.configuration</b> system property.</i> In case the system
property <b>log4j.configuration</b> is not defined, then set the
string variable <tt>resource</tt> to its default value
&quot;log4j.properties&quot;.</li>
<li>Attempt to convert the <tt>resource</tt> variable to a
URL.</li>
<li>If the resource variable cannot be converted to a URL, for
example due to a <tt>MalformedURLException</tt>, then search for
the <tt>resource</tt> from the classpath by calling
<tt>org.apache.log4j.helpers.Loader.getResource(resource,
Logger.class)</tt> which returns a URL. Note that the string
&quot;log4j.properties&quot; constitutes a malformed URL.
<p>See <a href="apidocs/org/apache/log4j/helpers/Loader.html#getResourcejava.lang.String">Loader.getResource(java.lang.String)</a>
for the list of searched locations.</p></li>
<li>If no URL could not be found, abort default
initialization. Otherwise, configure log4j from the URL.
<p>The <a href="apidocs/org/apache/log4j/PropertyConfigurator.html">PropertyConfigurator</a>
will be used to parse the URL to configure log4j unless the URL ends
with the &quot;.xml&quot; extension, in which case the <a href="apidocs/org/apache/log4j/xml/DOMConfigurator.html">DOMConfigurator</a>
will be used. You can optionaly specify a custom configurator. The
value of the <b>log4j.configuratorClass</b> system property is taken
as the fully qualified class name of your custom configurator. The
custom configurator you specify <i>must</i> implement the <a href="apidocs/org/apache/log4j/spi/Configurator.html">Configurator</a>
interface.</p></li>
</ol>
<div class="section"><h2>Example Configurations<a name="Example_Configurations"></a></h2>
<div class="section"><h2>Default Initialization under Tomcat<a name="Default_Initialization_under_Tomcat"></a></h2>
<p>The default log4j initialization is particularly useful in
web-server environments. Under Tomcat 3.x and 4.x, you should place
the <tt>log4j.properties</tt> under the
<tt>WEB-INF/classes</tt> directory of your web-applications. Log4j
will find the properties file and initialize itself. This is easy to
do and it works.</p>
<p>You can also choose to set the system property
<b>log4j.configuration</b> before starting Tomcat. For Tomcat 3.x The
<tt>TOMCAT_OPTS</tt> environment variable is used to set command
line options. For Tomcat 4.0, set the <tt>CATALINA_OPTS</tt>
environment variable instead of <tt>TOMCAT_OPTS</tt>.</p>
<p><b>Example 1</b></p>
<p>The Unix shell command
</p><div><pre>
export TOMCAT_OPTS=&quot;-Dlog4j.configuration=foobar.txt&quot;
</pre></div>
tells log4j to use the file <tt>foobar.txt</tt> as the default
configuration file. This file should be place under the
<tt>WEB-INF/classes</tt> directory of your web-application. The
file will be read using the <a href="apidocs/org/apache/log4j/PropertyConfigurator.html">PropertyConfigurator</a>. Each
web-application will use a different default configuration file because
each file is relative to a web-application.
<p><b>Example 2</b></p>
<p>The Unix shell command
</p><div><pre>
export TOMCAT_OPTS=&quot;-Dlog4j.debug -Dlog4j.configuration=foobar.xml&quot;
</pre></div>
tells log4j to output log4j-internal debugging information and to use
the file <tt>foobar.xml</tt> as the default configuration
file. This file should be place under the <tt>WEB-INF/classes</tt>
directory of your web-application. Since the file ends with a
<tt>.xml</tt> extension, it will read using the <a href="apidocs/org/apache/log4j/xml/DOMConfigurator.html">DOMConfigurator</a>. Each
web-application will use a different default configuration file because
each file is relative to a web-application.
<p><b>Example 3</b></p>
<p>The Windows shell command
</p><div><pre>
set TOMCAT_OPTS=-Dlog4j.configuration=foobar.lcf -Dlog4j.configuratorClass=com.foo.BarConfigurator
</pre></div>
tells log4j to use the file <tt>foobar.lcf</tt> as the default
configuration file. This file should be place under the
<tt>WEB-INF/classes</tt> directory of your web-application. Due to
the definition of the <b>log4j.configuratorClass</b> system property,
the file will be read using the <tt>com.foo.BarConfigurator</tt>
custom configurator. Each web-application will use a different
default configuration file because each file is relative to a
web-application.
<p><b>Example 4</b></p>
<p>The Windows shell command
</p><div><pre>
set TOMCAT_OPTS=-Dlog4j.configuration=file:/c:/foobar.lcf</pre></div>
tells log4j to use the file <tt>c:\foobar.lcf</tt> as the default
configuration file. The configuration file is fully specified by the
URL <tt>file:/c:/foobar.lcf</tt>. Thus, the same configuration
file will be used for all web-applications.
<p>Different web-applications will load the log4j classes through
their respective classloaderss. Thus, each image of the log4j
environment will act independetly and without any mutual
synchronization. For example, <tt>FileAppenders</tt> defined
exactly the same way in multiple web-application configurations will
all attempt to write the same file. The results are likely to be less
than satisfactory. You must make sure that log4j configurations of
different web-applications do not use the same underlying system
resource.</p>
<p><b>Initialization servlet</b></p>
<p>It is also possible to use a special servlet for log4j
initialization. Here is an example,</p>
<p></p><table border="0" class="bodyTable" bgcolor="CCCCCC"><tr class="a"><td>
<div><pre>
package com.foo;
import org.apache.log4j.PropertyConfigurator;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.IOException;
public class Log4jInit extends HttpServlet {
public
void <b>init()</b> {
String prefix = getServletContext().getRealPath(&quot;/&quot;);
String file = getInitParameter(&quot;log4j-init-file&quot;);
// if the log4j-init-file is not set, then no point in trying
if(file != null) {
PropertyConfigurator.configure(prefix+file);
}
}
public
void doGet(HttpServletRequest req, HttpServletResponse res) {
}
}
</pre></div>
</td></tr></table>
<p>Define the following servlet in the web.xml file for your web-application.</p>
<p></p><table border="0" class="bodyTable" bgcolor="CCAAAA"><tr class="a"><td>
<div><pre>
&lt;servlet&gt;
&lt;servlet-name&gt;log4j-init&lt;/servlet-name&gt;
&lt;servlet-class&gt;com.foo.Log4jInit&lt;/servlet-class&gt;
&lt;init-param&gt;
&lt;param-name&gt;log4j-init-file&lt;/param-name&gt;
&lt;param-value&gt;WEB-INF/classes/log4j.lcf&lt;/param-value&gt;
&lt;/init-param&gt;
<b>&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;</b>
&lt;/servlet&gt;
</pre></div>
</td></tr></table>
<p>Writing an initialization servlet is the most flexible way for
initializing log4j. There are no constraints on the code you can place
in the <tt>init()</tt> method of the servlet.</p>
<div class="section"><h2> Nested Diagnostic Contexts<a name="Nested_Diagnostic_Contexts"></a></h2>
<p>Most real-world systems have to deal with multiple clients
simultaneously. In a typical multithreaded implementation of such a
system, different threads will handle different clients. Logging is
especially well suited to trace and debug complex distributed
applications. A common approach to differentiate the logging output of
one client from another is to instantiate a new separate logger for
each client. This promotes the proliferation of loggers and
increases the management overhead of logging.</p>
<p>A lighter technique is to uniquely stamp each log request initiated
from the same client interaction. Neil Harrison described this method
in the book &quot;Patterns for Logging Diagnostic Messages,&quot; in <i>Pattern
Languages of Program Design 3</i>, edited by R. Martin, D. Riehle,
and F. Buschmann (Addison-Wesley, 1997).</p>
<p> To uniquely stamp each request, the
user pushes contextual information into the NDC, the abbreviation of
<i>Nested Diagnostic Context</i>. The NDC class is shown below.
</p><div><pre>
public class NDC {
// Used when printing the diagnostic
public <b>static</b> String get();
// Remove the top of the context from the NDC.
public <b>static</b> String pop();
// Add diagnostic context for the current thread.
public <b>static</b> void push(String message);
// Remove the diagnostic context for this thread.
public <b>static</b> void remove();
}
</pre></div>
<p>The NDC is managed per thread as a <i>stack</i> of contextual
information. Note that all methods of the <tt>org.apache.log4j.NDC</tt>
class are static. Assuming that NDC printing is turned on, every time
a log request is made, the appropriate log4j component will include
the <i>entire</i> NDC stack for the current thread in the log
output. This is done without the intervention of the user, who is
responsible only for placing the correct information in the NDC by
using the <tt>push</tt> and <tt>pop</tt> methods at a few
well-defined points in the code. In contrast, the per-client logger
approach commands extensive changes in the code.</p>
<p>To illustrate this point, let us take the example of a servlet
delivering content to numerous clients. The servlet can build the NDC
at the very beginning of the request before executing other code. The
contextual information can be the client's host name and other
information inherent to the request, typically information contained
in cookies. Hence, even if the servlet is serving multiple clients
simultaneously, the logs initiated by the same code, i.e. belonging to
the same logger, can still be distinguished because each client
request will have a different NDC stack. Contrast this with the
complexity of passing a freshly instantiated logger to all code
exercised during the client's request.</p>
<p>Nevertheless, some sophisticated applications, such as virtual
hosting web servers, must log differently depending on the virtual
host context and also depending on the software component issuing the
request. Recent log4j releases support multiple hierarchy trees. This
enhancement allows each virtual host to possess its own copy of the
logger hierarchy.</p>
<a name="performance"></a><div class="section"><h2>Performance<a name="Performance"></a></h2>
<p>One of the often-cited arguments against logging is its
computational cost. This is a legitimate concern as even moderately
sized applications can generate thousands of log requests. Much
effort was spent measuring and tweaking logging performance. Log4j
claims to be fast and flexible: speed first, flexibility second.</p>
<p>The user should be aware of the following performance issues.</p>
<ol style="list-style-type: decimal">
<li><b>Logging performance when logging is turned off.</b><br />
<p>When logging is turned
off entirely or just for a <a href="apidocs/org/apache/log4j/Hierarchy.html#setThresholdjava.lang.String">set
of levels</a>, the cost of a log request consists of a method
invocation plus an integer comparison. On a 233 MHz Pentium II
machine this cost is typically in the 5 to 50 nanosecond range.</p>
<p>However, The method invocation involves the &quot;hidden&quot; cost of
parameter construction.</p>
<p>For example, for some logger <tt>cat</tt>, writing,
</p><div><pre>
logger.debug(&quot;Entry number: &quot; + i + &quot; is &quot; + String.valueOf(entry[i]));
</pre></div>
incurs the cost of constructing the message parameter, i.e.
converting both integer <tt>i</tt> and <tt>entry[i]</tt>
to a String, and concatenating intermediate strings,
regardless of whether the message will be logged or not.
This cost of parameter construction can be quite high and it
depends on the size of the parameters involved.
<p>To avoid the parameter construction cost write:
</p><div><pre>
if(logger.isDebugEnabled() {
logger.debug(&quot;Entry number: &quot; + i + &quot; is &quot; + String.valueOf(entry[i]));
}
</pre></div>
<p>This will not incur the cost of parameter
construction if debugging is disabled. On the other hand, if
the logger is debug-enabled, it will incur twice the cost of
evaluating whether the logger is enabled or not: once
in <tt>debugEnabled</tt> and once in
<tt>debug</tt>. This is an insignificant
overhead because evaluating a logger takes about 1%
of the time it takes to actually log.</p>
<p>In log4j, logging requests are made to instances of the Logger
class. Logger is a class and not an interface. This measurably
reduces the cost of method invocation at the cost of some
flexibility.</p>
<p>Certain users resort to preprocessing or compile-time
techniques to compile out all log statements. This leads to perfect
performance efficiency with respect to logging. However, since the
resulting application binary does not contain any log statements,
logging cannot be turned on for that binary. In my opinion this is
a disproportionate price to pay in exchange for a small performance
gain.</p></li>
<li><b>The performance of deciding whether to log or not to log when
logging is turned on.</b><br />
<p>This is essentially the performance of walking the logger
hierarchy. When logging is turned on, log4j still needs to compare
the level of the log request with the level of the request
logger. However, loggers may not have an assigned
level; they can inherit them from the logger hierarchy. Thus,
before inheriting a level, the logger may need to search its
ancestors.</p>
<p>There has been a serious effort to make this hierarchy walk to
be as fast as possible. For example, child loggers link only to
their existing ancestors. In the <tt>BasicConfigurator</tt>
example shown earlier, the logger named <tt>com.foo.Bar</tt> is
linked directly to the root logger, thereby circumventing the
nonexistent <tt>com</tt> or <tt>com.foo</tt> loggers. This
significantly improves the speed of the walk, especially in &quot;sparse&quot;
hierarchies.</p>
<p>The typical cost of walking the hierarchy is typically 3
times slower than when logging is turned off entirely.</p></li>
<li><b>Actually outputting log messages</b><br />
<p>This is the cost of formatting the log output and sending it to
its target destination. Here again, a serious effort was made to
make layouts (formatters) perform as quickly as possible. The same
is true for appenders. The typical cost of actually logging is
about 100 to 300 microseconds.</p>
See <a href="apidocs/org/apache/log4j/performance/Logging.html">org.apache.log4.performance.Logging</a>
for actual figures.
</li>
</ol>
<p>Although log4j has many features, its first design goal was speed.
Some log4j components have been rewritten many times to improve
performance. Nevertheless, contributors frequently come up with new
optimizations. You should be pleased to know that when configured with
the <a href="apidocs/org/apache/log4j/SimpleLayout.html">SimpleLayout</a>
performance tests have shown log4j to log as quickly as
<tt>System.out.println</tt>.</p>
<div class="section"><h2>Conclusions<a name="Conclusions"></a></h2>
<p>Log4j is a popular logging package written in Java. One of its
distinctive features is the notion of inheritance in loggers. Using
a logger hierarchy it is possible to control which log statements
are output at arbitrary granularity. This helps reduce the volume of
logged output and minimize the cost of logging.</p>
<p>One of the advantages of the log4j API is its manageability. Once
the log statements have been inserted into the code, they can be
controlled with configuration files. They can be selectively enabled
or disabled, and sent to different and multiple output targets in
user-chosen formats. The log4j package is designed so that log
statements can remain in shipped code without incurring a heavy
performance cost.</p>
<div class="section"><h2>Acknowledgments<a name="Acknowledgments"></a></h2>
Many thanks to N. Asokan for reviewing the article. He is also one of
the originators of the logger concept. I am indebted to Nelson Minar
for encouraging me to write this article. He has also made many useful
suggestions and corrections to this article. Log4j is the result of a
collective effort. My special thanks go to all the authors who have
contributed to the project. Without exception, the best features in
the package have all originated in the user community.
</div>
</div>
</div>
<div class="clear">
<hr/>
</div>
<div id="footer">
<div class="xleft">Copyright &#169; 1999-2012
<a href="http://www.apache.org">Apache Software Foundation</a>.
Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache Software License, Version 2.0</a>.</div>
<div class="xleft">Apache Extras Companion for Apache log4j, Apache log4j, Apache, the Apache feather logo,
the Apache Logging Services project logo, the log4j logo, and the Built by Maven logo are trademarks of The Apache Software Foundation. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.</div>
<div class="clear">
<hr/>
</div>
</div>
</body>
</html>