blob: 8ea6539812b6e920ff7531d82102a8dd52b8e893 [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 2018-03-17 -->
<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>Log4j &#x2013; Log4j 2 API - Apache Log4j 2</title>
<link rel="stylesheet" href="../css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="../css/site.css" type="text/css" />
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script type="text/javascript" src="../js/bootstrap.min.js"></script>
<script type="text/javascript" src="../js/prettify.min.js"></script>
<script type="text/javascript" src="../js/site.js"></script>
<meta name="author" content="Ralph Goers" />
<meta name="author" content="Gary Gregory" />
<meta name="Date-Revision-yyyymmdd" content="20180317" />
<meta http-equiv="Content-Language" content="en" />
</head>
<body class="composite">
<a href="https://logging.apache.org/">
<img class="logo-left" src="../images/ls-logo.jpg" alt="Apache logging services logo" />
</a>
<img class="logo-right" src="../images/logo.png" alt="Apache log4j logo" />
<div class="clear"></div>
<div class="navbar">
<div class="navbar-inner">
<div class="container-fluid">
<a class="brand" href="https://logging.apache.org/log4j/2.x/">Apache Log4j 2 &trade;</a>
<ul class="nav">
<li>
<a href="https://cwiki.apache.org/confluence/display/LOGGING/Log4j" class="external" target="_blank" title="Logging Wiki">Logging Wiki</a>
</li>
<li>
<a href="https://www.apache.org/" class="external" target="_blank" title="Apache">Apache</a>
</li>
<li>
<a href="../../../" title="Logging Services">Logging Services</a>
</li>
<li>
<a href="https://analysis.apache.org/dashboard/index/org.apache.logging.log4j:log4j" class="external" target="_blank" title="Sonar">Sonar</a>
</li>
<li>
<a href="https://github.com/apache/logging-log4j2" class="external" target="_blank" title="GitHub">GitHub</a>
</li>
</ul>
</div>
</div>
</div>
<div class="container-fluid">
<table class="layout-table">
<tr>
<td class="sidebar">
<div class="well sidebar-nav">
<ul class="nav nav-list">
<li class="nav-header"><i class="icon-home"></i>Apache Log4j™ 2</li>
<li class="none">
<a href="../index.html" title="About">About</a>
</li>
<li class="none">
<a href="../download.html" title="Download">Download</a>
</li>
<li class="collapsed">
<a href="../javadoc.html" title="Javadoc">Javadoc</a>
</li>
<li class="collapsed">
<a href="../maven-artifacts.html" title="Maven, Ivy, Gradle Artifacts">Maven, Ivy, Gradle Artifacts</a>
</li>
<li class="none">
<a href="../runtime-dependencies.html" title="Runtime Dependencies">Runtime Dependencies</a>
</li>
<li class="none">
<a href="../changelog.html" title="Changelog">Changelog</a>
</li>
<li class="none">
<a href="../faq.html" title="FAQ">FAQ</a>
</li>
<li class="collapsed">
<a href="../performance.html" title="Performance">Performance</a>
</li>
<li class="none">
<a href="../articles.html" title="Articles and Tutorials">Articles and Tutorials</a>
</li>
<li class="none">
<a href="../thanks.html" title="Thanks">Thanks</a>
</li>
</ul>
<ul class="nav nav-list">
<li class="nav-header"><i class="icon-pencil"></i>For Contributors</li>
<li class="none">
<a href="../build.html" title="Building Log4j from Source">Building Log4j from Source</a>
</li>
<li class="none">
<a href="../guidelines.html" title="Guidelines">Guidelines</a>
</li>
<li class="none">
<a href="../javastyle.html" title="Style Guide">Style Guide</a>
</li>
</ul>
<ul class="nav nav-list">
<li class="nav-header"><i class="icon-book"></i>Manual</li>
<li class="none">
<a href="../manual/index.html" title="Introduction">Introduction</a>
</li>
<li class="none">
<a href="../manual/architecture.html" title="Architecture">Architecture</a>
</li>
<li class="none">
<a href="../manual/migration.html" title="Log4j 1.x Migration">Log4j 1.x Migration</a>
</li>
<li class="expanded active">
<a href="../manual/api.html" title="Java API">Java API</a>
<ul>
<li class="none">
<a href="../manual/flowtracing.html" title="Flow Tracing">Flow Tracing</a>
</li>
<li class="none">
<a href="../manual/markers.html" title="Markers">Markers</a>
</li>
<li class="none">
<a href="../manual/eventlogging.html" title="Event Logging">Event Logging</a>
</li>
<li class="none">
<a href="../manual/messages.html" title="Messages">Messages</a>
</li>
<li class="none">
<a href="../manual/thread-context.html" title="ThreadContext">ThreadContext</a>
</li>
</ul>
</li>
<li class="none">
<a href="../manual/scala-api.html" title="Scala API">Scala API</a>
</li>
<li class="collapsed">
<a href="../manual/configuration.html" title="Configuration">Configuration</a>
</li>
<li class="collapsed">
<a href="../manual/webapp.html" title="Web Applications and JSPs">Web Applications and JSPs</a>
</li>
<li class="collapsed">
<a href="../manual/lookups.html" title="Lookups">Lookups</a>
</li>
<li class="collapsed">
<a href="../manual/appenders.html" title="Appenders">Appenders</a>
</li>
<li class="collapsed">
<a href="../manual/layouts.html" title="Layouts">Layouts</a>
</li>
<li class="collapsed">
<a href="../manual/filters.html" title="Filters">Filters</a>
</li>
<li class="collapsed">
<a href="../manual/async.html" title="Async Loggers">Async Loggers</a>
</li>
<li class="collapsed">
<a href="../manual/garbagefree.html" title="Garbage-free Logging">Garbage-free Logging</a>
</li>
<li class="none">
<a href="../manual/jmx.html" title="JMX">JMX</a>
</li>
<li class="none">
<a href="../manual/logsep.html" title="Logging Separation">Logging Separation</a>
</li>
<li class="collapsed">
<a href="../manual/extending.html" title="Extending Log4j">Extending Log4j</a>
</li>
<li class="collapsed">
<a href="../manual/plugins.html" title="Plugins">Plugins</a>
</li>
<li class="collapsed">
<a href="../manual/customconfig.html" title="Programmatic Log4j Configuration">Programmatic Log4j Configuration</a>
</li>
<li class="collapsed">
<a href="../manual/customloglevels.html" title="Custom Log Levels">Custom Log Levels</a>
</li>
</ul>
<ul class="nav nav-list">
<li class="nav-header"><i class="icon-tags"></i>Related Projects</li>
<li class="none">
<a href="http://logging.apache.org/log4j/scala/index.html" class="external" target="_blank" title="Log4j-Scala">Log4j-Scala</a>
</li>
</ul>
<ul class="nav nav-list">
<li class="nav-header"><i class="icon-tags"></i>Legacy</li>
<li class="none">
<a href="http://logging.apache.org/log4j/1.2/" class="external" target="_blank" title="Log4j 1.2">Log4j 1.2</a>
</li>
<li class="none">
<a href="http://logging.apache.org/log4j/log4j-2.3/" class="external" target="_blank" title="Log4j 2.3">Log4j 2.3</a>
</li>
</ul>
<ul class="nav nav-list">
<li class="nav-header"><i class="icon-cog"></i>Components</li>
<li class="none">
<a href="../log4j-api/index.html" title="API">API</a>
</li>
<li class="none">
<a href="../log4j-core/index.html" title="Implementation">Implementation</a>
</li>
<li class="none">
<a href="../log4j-jcl/index.html" title="Commons Logging Bridge">Commons Logging Bridge</a>
</li>
<li class="none">
<a href="../log4j-1.2-api/index.html" title="Log4j 1.2 API">Log4j 1.2 API</a>
</li>
<li class="none">
<a href="../log4j-slf4j-impl/index.html" title="SLF4J Binding">SLF4J Binding</a>
</li>
<li class="none">
<a href="../log4j-jul/index.html" title="JUL Adapter">JUL Adapter</a>
</li>
<li class="none">
<a href="../log4j-to-slf4j/index.html" title="Log4j 2 to SLF4J Adapter">Log4j 2 to SLF4J Adapter</a>
</li>
<li class="none">
<a href="../log4j-flume-ng/index.html" title="Apache Flume Appender">Apache Flume Appender</a>
</li>
<li class="none">
<a href="../log4j-taglib/index.html" title="Log4j Tag Library">Log4j Tag Library</a>
</li>
<li class="none">
<a href="../log4j-jmx-gui/index.html" title="Log4j JMX GUI">Log4j JMX GUI</a>
</li>
<li class="none">
<a href="../log4j-web/index.html" title="Log4j Web Application Support">Log4j Web Application Support</a>
</li>
<li class="none">
<a href="../log4j-appserver/index.html" title="Log4j Application Server Integration">Log4j Application Server Integration</a>
</li>
<li class="none">
<a href="../log4j-couchdb/index.html" title="Log4j CouchDB appender">Log4j CouchDB appender</a>
</li>
<li class="none">
<a href="../log4j-mongodb2/index.html" title="Log4j MongoDB2 appender">Log4j MongoDB2 appender</a>
</li>
<li class="none">
<a href="../log4j-mongodb3/index.html" title="Log4j MongoDB3 appender">Log4j MongoDB3 appender</a>
</li>
<li class="none">
<a href="../log4j-cassandra/index.html" title="Log4j Cassandra appender">Log4j Cassandra appender</a>
</li>
<li class="none">
<a href="../log4j-iostreams/index.html" title="Log4j IO Streams">Log4j IO Streams</a>
</li>
<li class="none">
<a href="../log4j-liquibase/index.html" title="Log4j Liquibase Binding">Log4j Liquibase Binding</a>
</li>
</ul>
<ul class="nav nav-list">
<li class="nav-header"><i class="icon-info-sign"></i>Project Information</li>
<li class="none">
<a href="../dependency-convergence.html" title="Dependency Convergence">Dependency Convergence</a>
</li>
<li class="none">
<a href="../dependency-management.html" title="Dependency Management">Dependency Management</a>
</li>
<li class="none">
<a href="../team-list.html" title="Project Team">Project Team</a>
</li>
<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="../license.html" title="Project License">Project License</a>
</li>
<li class="none">
<a href="../source-repository.html" title="Source Repository">Source Repository</a>
</li>
<li class="none">
<a href="../project-summary.html" title="Project Summary">Project Summary</a>
</li>
</ul>
<ul class="nav nav-list">
<li class="nav-header"><i class="icon-cog"></i>Project Reports</li>
<li class="none">
<a href="../changes-report.html" title="Changes Report">Changes Report</a>
</li>
<li class="none">
<a href="../jira-report.html" title="JIRA Report">JIRA Report</a>
</li>
<li class="none">
<a href="../rat-report.html" title="RAT Report">RAT Report</a>
</li>
</ul>
</div>
<div id="poweredBy">
<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>
</td>
<td class="content">
<!-- 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 class="section">
<h2><a name="Log4j_2_API"></a>Log4j 2 API</h2>
<a name="Overview"></a>
<div class="section">
<h3><a name="Overview"></a>Overview</h3>
<p>
The Log4j 2 API provides the interface that applications should code to and provides the
adapter components required for implementers to create a logging implementation. Although Log4j 2
is broken up between an API and an implementation, the primary purpose of doing so was not to
allow multiple implementations, although that is certainly possible, but to clearly define
what classes and methods are safe to use in &quot;normal&quot; application code.
</p>
<div class="section">
<h4><a name="Hello_World"></a>Hello World!</h4>
<p>
No introduction would be complete without the customary Hello, World example. Here is ours. First,
a Logger with the name &quot;HelloWorld&quot; is obtained from the
<a href="../log4j-api/apidocs/org/apache/logging/log4j/LogManager.html">LogManager</a>.
Next, the logger is used to write the &quot;Hello, World!&quot; message, however the message will be written
only if the Logger is configured to allow informational messages.
</p>
<div>
<pre class="prettyprint linenums">import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class HelloWorld {
private static final Logger logger = LogManager.getLogger(&quot;HelloWorld&quot;);
public static void main(String[] args) {
logger.info(&quot;Hello, World!&quot;);
}
}</pre></div>
<p>
The output from the call to logger.info() will vary significantly depending on the configuration
used. See the <a href="./configuration.html">Configuration</a> section for more details.
</p>
</div>
<div class="section">
<h4><a name="Substituting_Parameters"></a>Substituting Parameters</h4>
<p>
Frequently the purpose of logging is to provide information about what is happening in the system,
which requires including information about the objects being manipulated. In Log4j 1.x this could
be accomplished by doing:
</p>
<div>
<pre class="prettyprint linenums">if (logger.isDebugEnabled()) {
logger.debug(&quot;Logging in user &quot; + user.getName() + &quot; with birthday &quot; + user.getBirthdayCalendar());
}</pre></div>
<p>
Doing this repeatedly has the effect of making the code feel like it is more about logging than the
actual task at hand. In addition, it results in the logging level being checked twice; once on the
call to isDebugEnabled and once on the debug method. A better alternative would be:
</p>
<div>
<pre class="prettyprint">logger.debug(&quot;Logging in user {} with birthday {}&quot;, user.getName(), user.getBirthdayCalendar());</pre></div>
<p>
With the code above the logging level will only be checked once and the String construction will
only occur when debug logging is enabled.
</p>
</div>
<div class="section">
<h4><a name="Formatting_Parameters"></a>Formatting Parameters</h4>
<p>
Formatter Loggers leave formatting up to you if <tt>toString()</tt> is not what you want.
To facilitate formatting, you can use the same format strings as Java's
<a class="externalLink" href="http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax">Formatter</a>.
For example:
</p>
<div>
<pre class="prettyprint linenums">public static Logger logger = LogManager.getFormatterLogger(&quot;Foo&quot;);
logger.debug(&quot;Logging in user %s with birthday %s&quot;, user.getName(), user.getBirthdayCalendar());
logger.debug(&quot;Logging in user %1$s with birthday %2$tm %2$te,%2$tY&quot;, user.getName(), user.getBirthdayCalendar());
logger.debug(&quot;Integer.MAX_VALUE = %,d&quot;, Integer.MAX_VALUE);
logger.debug(&quot;Long.MAX_VALUE = %,d&quot;, Long.MAX_VALUE);
</pre></div>
<p>
To use a formatter Logger, you must call one of the LogManager
<a href="../log4j-api/apidocs/org/apache/logging/log4j/LogManager.html#getFormatterLoggerjava.lang.Class">getFormatterLogger</a>
methods. The output for this example shows that Calendar toString() is verbose compared to custom formatting:
</p>
<div>
<pre class="prettyprint linenums">2012-12-12 11:56:19,633 [main] DEBUG: User John Smith with birthday java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id=&quot;America/New_York&quot;,offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=?,YEAR=1995,MONTH=4,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=23,DAY_OF_YEAR=?,DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFSET=?,DST_OFFSET=?]
2012-12-12 11:56:19,643 [main] DEBUG: User John Smith with birthday 05 23, 1995
2012-12-12 11:56:19,643 [main] DEBUG: Integer.MAX_VALUE = 2,147,483,647
2012-12-12 11:56:19,643 [main] DEBUG: Long.MAX_VALUE = 9,223,372,036,854,775,807
</pre></div>
</div>
<div class="section">
<h4><a name="Mixing_Loggers_with_Formatter_Loggers"></a>Mixing Loggers with Formatter Loggers</h4>
<p>
Formatter loggers give fine-grained control over the output format, but have the drawback
that the correct type must be specified (for example, passing anything other than a decimal integer
for a %d format parameter gives an exception).
</p>
<p>
If your main usage is to use {}-style parameters, but occasionally you need fine-grained
control over the output format, you can use the <tt>printf</tt> method:</p>
<div>
<pre class="prettyprint linenums">public static Logger logger = LogManager.getLogger(&quot;Foo&quot;);
logger.debug(&quot;Opening connection to {}...&quot;, someDataSource);
logger.printf(Level.INFO, &quot;Logging in user %1$s with birthday %2$tm %2$te,%2$tY&quot;, user.getName(), user.getBirthdayCalendar());
</pre></div>
<a name="LambdaSupport"></a>
</div>
<div class="section">
<h4><a name="Java_8_lambda_support_for_lazy_logging"></a>Java 8 lambda support for lazy logging</h4>
<p>
In release 2.4, the <tt>Logger</tt> interface added support for lambda expressions.
This allows client code to lazily log messages without explicitly checking if the requested log
level is enabled. For example, previously you would write:
</p>
<div>
<pre class="prettyprint linenums">// pre-Java 8 style optimization: explicitly check the log level
// to make sure the expensiveOperation() method is only called if necessary
if (logger.isTraceEnabled()) {
logger.trace(&quot;Some long-running operation returned {}&quot;, expensiveOperation());
}</pre></div>
<p>
With Java 8 you can achieve the same effect with a lambda expression.
You no longer need to explicitly check the log level:
</p>
<div>
<pre class="prettyprint linenums">// Java-8 style optimization: no need to explicitly check the log level:
// the lambda expression is not evaluated if the TRACE level is not enabled
logger.trace(&quot;Some long-running operation returned {}&quot;, () -&gt; expensiveOperation());</pre></div>
</div>
<div class="section">
<h4><a name="Logger_Names"></a>Logger Names</h4>
<p>
Most logging implementations use a hierarchical scheme for matching logger names with logging
configuration. In this scheme, the logger name hierarchy is represented by <tt>'.'</tt> characters
in the logger name, in a fashion very similar to the hierarchy used for Java package names. For example,
<tt>org.apache.logging.appender</tt> and <tt>org.apache.logging.filter</tt> both have
<tt>org.apache.logging</tt> as their parent. In most cases, applications name their loggers by
passing the current class's name to <tt>LogManager.getLogger(...)</tt>. Because this usage is so
common, Log4j 2 provides that as the default when the logger name parameter is either omitted or is
null. For example, in all examples below the Logger will have a name of
<tt>&quot;org.apache.test.MyTest&quot;</tt>.
</p>
<div>
<pre class="prettyprint linenums">package org.apache.test;
public class MyTest {
private static final Logger logger = LogManager.getLogger(MyTest.class);
}</pre></div>
<div>
<pre class="prettyprint linenums">package org.apache.test;
public class MyTest {
private static final Logger logger = LogManager.getLogger(MyTest.class.getName());
}</pre></div>
<div>
<pre class="prettyprint linenums">package org.apache.test;
public class MyTest {
private static final Logger logger = LogManager.getLogger();
}</pre></div>
</div></div>
</div>
</td>
</tr>
</table>
</div>
<div class="footer">
<p>Copyright &copy; 1999-2018 <a class="external" href="https://www.apache.org/">The Apache Software Foundation</a>. All Rights Reserved.</p>
<p>Apache Logging, Apache Log4j, Log4j, Apache, the Apache feather logo, and the Apache Logging project logo are trademarks of The Apache Software Foundation.</p>
<p>Site powered by <a class="external" href="http://getbootstrap.com/">Twitter Bootstrap</a>. Icons from <a class="external" href="http://glyphicons.com/">Glyphicons Free</a>.</p>
</div>
</div>
</body>
</html>