blob: 6892cdebdf84c13a4b60c1d24739053c5adb21d1 [file] [log] [blame]
<!DOCTYPE html>
<!--
| Generated by Apache Maven Doxia Site Renderer 1.9.1 from src/site/xdoc/manual/customconfig.xml at 2019-12-11
| Rendered using Apache Maven Fluido Skin 1.8
-->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="generator" content="Apache Maven Doxia Site Renderer 1.9.1" />
<meta name="author" content="Ralph Goers" />
<title>Log4j &#x2013; Extending Log4j 2 Configuration</title>
<link rel="stylesheet" href="../css/apache-maven-fluido-1.8.min.css" />
<link rel="stylesheet" href="../css/site.css" />
<link rel="stylesheet" href="../css/print.css" media="print" />
<script src="../js/apache-maven-fluido-1.8.min.js"></script>
</head>
<body class="topBarDisabled">
<div class="container-fluid">
<header>
<div id="banner">
<div class="pull-left"><a href="http://logging.apache.org" id="bannerLeft"><img src="../images/ls-logo.jpg" alt=""/></a></div>
<div class="pull-right"><a href="http://logging.apache.org/log4j/2.x" id="bannerRight"><img src="../images/logo.png" alt=""/></a></div>
<div class="clear"><hr/></div>
</div>
<div id="breadcrumbs">
<ul class="breadcrumb">
<li id="publishDate">Last Published: 2019-12-11<span class="divider">|</span>
</li>
<li id="projectVersion">Version: 2.13.0</li>
<li class="pull-right"><span class="divider">|</span>
<a href="https://github.com/apache/logging-log4j2" class="externalLink" title="GitHub">GitHub</a></li>
<li class="pull-right"><span class="divider">|</span>
<a href="https://analysis.apache.org/dashboard/index/org.apache.logging.log4j:log4j" class="externalLink" title="Sonar">Sonar</a></li>
<li class="pull-right"><span class="divider">|</span>
<a href="../../../" title="Logging Services">Logging Services</a></li>
<li class="pull-right"><span class="divider">|</span>
<a href="https://www.apache.org/" class="externalLink" title="Apache">Apache</a></li>
<li class="pull-right"><a href="https://cwiki.apache.org/confluence/display/LOGGING/Log4j" class="externalLink" title="Logging Wiki">Logging Wiki</a></li>
</ul>
</div>
</header>
<div class="row-fluid">
<header id="leftColumn" class="span2">
<nav class="well sidebar-nav">
<ul class="nav nav-list">
<li class="nav-header"><img class="imageLink" src="../img/glyphicons/home.png" alt="Apache Log4j™ 2" border="0"/> Apache Log4j™ 2</li>
<li><a href="../index.html" title="About"><span class="none"></span>About</a></li>
<li><a href="../download.html" title="Download"><span class="none"></span>Download</a></li>
<li><a href="../javadoc.html" title="Javadoc"><span class="icon-chevron-right"></span>Javadoc</a></li>
<li><a href="../maven-artifacts.html" title="Maven, Ivy, Gradle Artifacts"><span class="icon-chevron-right"></span>Maven, Ivy, Gradle Artifacts</a></li>
<li><a href="../runtime-dependencies.html" title="Runtime Dependencies"><span class="none"></span>Runtime Dependencies</a></li>
<li><a href="../changelog.html" title="Changelog"><span class="none"></span>Changelog</a></li>
<li><a href="../faq.html" title="FAQ"><span class="none"></span>FAQ</a></li>
<li><a href="../performance.html" title="Performance"><span class="icon-chevron-right"></span>Performance</a></li>
<li><a href="../articles.html" title="Articles and Tutorials"><span class="none"></span>Articles and Tutorials</a></li>
<li><a href="../thanks.html" title="Thanks"><span class="none"></span>Thanks</a></li>
<li class="nav-header"><img class="imageLink" src="../img/glyphicons/pencil.png" alt="For Contributors" border="0"/> For Contributors</li>
<li><a href="../build.html" title="Building Log4j from Source"><span class="none"></span>Building Log4j from Source</a></li>
<li><a href="../guidelines.html" title="Guidelines"><span class="none"></span>Guidelines</a></li>
<li><a href="../javastyle.html" title="Style Guide"><span class="none"></span>Style Guide</a></li>
<li class="nav-header"><img class="imageLink" src="../img/glyphicons/book.png" alt="Manual" border="0"/> Manual</li>
<li><a href="../manual/index.html" title="Introduction"><span class="none"></span>Introduction</a></li>
<li><a href="../manual/architecture.html" title="Architecture"><span class="none"></span>Architecture</a></li>
<li><a href="../manual/compatibility.html" title="Log4j 1.x Compatibility"><span class="none"></span>Log4j 1.x Compatibility</a></li>
<li><a href="../manual/migration.html" title="Log4j 1.x Migration"><span class="none"></span>Log4j 1.x Migration</a></li>
<li><a href="../manual/api.html" title="Java API"><span class="icon-chevron-right"></span>Java API</a></li>
<li><a href="../manual/scala-api.html" title="Scala API"><span class="none"></span>Scala API</a></li>
<li><a href="../manual/configuration.html" title="Configuration"><span class="icon-chevron-right"></span>Configuration</a></li>
<li><a href="../manual/usage.html" title="Usage"><span class="icon-chevron-right"></span>Usage</a></li>
<li><a href="../manual/webapp.html" title="Web Applications and JSPs"><span class="icon-chevron-right"></span>Web Applications and JSPs</a></li>
<li><a href="../manual/lookups.html" title="Lookups"><span class="icon-chevron-right"></span>Lookups</a></li>
<li><a href="../manual/appenders.html" title="Appenders"><span class="icon-chevron-right"></span>Appenders</a></li>
<li><a href="../manual/layouts.html" title="Layouts"><span class="icon-chevron-right"></span>Layouts</a></li>
<li><a href="../manual/filters.html" title="Filters"><span class="icon-chevron-right"></span>Filters</a></li>
<li><a href="../manual/async.html" title="Async Loggers"><span class="icon-chevron-right"></span>Async Loggers</a></li>
<li><a href="../manual/garbagefree.html" title="Garbage-free Logging"><span class="icon-chevron-right"></span>Garbage-free Logging</a></li>
<li><a href="../manual/jmx.html" title="JMX"><span class="none"></span>JMX</a></li>
<li><a href="../manual/logsep.html" title="Logging Separation"><span class="none"></span>Logging Separation</a></li>
<li><a href="../manual/extending.html" title="Extending Log4j"><span class="icon-chevron-right"></span>Extending Log4j</a></li>
<li><a href="../manual/plugins.html" title="Plugins"><span class="icon-chevron-right"></span>Plugins</a></li>
<li class="active"><a href="#"><span class="icon-chevron-down"></span>Programmatic Log4j Configuration</a>
<ul class="nav nav-list">
<li><a href="../manual/customconfig.html#ConfigurationBuilder" title="ConfigurationBuilder API"><span class="none"></span>ConfigurationBuilder API</a></li>
<li><a href="../manual/customconfig.html#ConfigurationFactory" title="Understanding ConfigurationFactory"><span class="none"></span>Understanding ConfigurationFactory</a></li>
<li><a href="../manual/customconfig.html#Example" title="Example"><span class="none"></span>Example</a></li>
<li><a href="../manual/customconfig.html#Configurator" title="Using Configurator"><span class="none"></span>Using Configurator</a></li>
<li><a href="../manual/customconfig.html#Hybrid" title="Config File and Code"><span class="none"></span>Config File and Code</a></li>
<li><a href="../manual/customconfig.html#AddingToCurrent" title="After Initialization"><span class="none"></span>After Initialization</a></li>
<li><a href="../manual/customconfig.html#AppendingToWritersAndOutputStreams" title="Appending to Writers & OutputStreams"><span class="none"></span>Appending to Writers & OutputStreams</a></li>
</ul></li>
<li><a href="../manual/customloglevels.html" title="Custom Log Levels"><span class="icon-chevron-right"></span>Custom Log Levels</a></li>
<li class="nav-header"><img class="imageLink" src="../img/glyphicons/tag.png" alt="Related Projects" border="0"/> Related Projects</li>
<li><a href="http://logging.apache.org/log4j/scala/index.html" class="externalLink" title="Log4j-Scala"><span class="none"></span>Log4j-Scala</a></li>
<li class="nav-header"><img class="imageLink" src="../img/glyphicons/link.png" alt="Legacy Sites" border="0"/> Legacy Sites</li>
<li><a href="http://logging.apache.org/log4j/1.2/" class="externalLink" title="Log4j 1.2 - End of Life"><span class="none"></span>Log4j 1.2 - End of Life</a></li>
<li><a href="http://logging.apache.org/log4j/log4j-2.3/" class="externalLink" title="Log4j 2.3 - Java 6"><span class="none"></span>Log4j 2.3 - Java 6</a></li>
<li><a href="http://logging.apache.org/log4j/log4j-2.12.1" class="externalLink" title="Log4j 2.12.1 - Java 7"><span class="none"></span>Log4j 2.12.1 - Java 7</a></li>
<li class="nav-header"><img class="imageLink" src="../img/glyphicons/cog.png" alt="Components" border="0"/> Components</li>
<li><a href="../log4j-api/index.html" title="API"><span class="none"></span>API</a></li>
<li><a href="../log4j-core/index.html" title="Implementation"><span class="none"></span>Implementation</a></li>
<li><a href="../log4j-jcl/index.html" title="Commons Logging Bridge"><span class="none"></span>Commons Logging Bridge</a></li>
<li><a href="../log4j-1.2-api/index.html" title="Log4j 1.2 API"><span class="none"></span>Log4j 1.2 API</a></li>
<li><a href="../log4j-slf4j-impl/index.html" title="SLF4J Binding"><span class="none"></span>SLF4J Binding</a></li>
<li><a href="../log4j-jul/index.html" title="JUL Adapter"><span class="none"></span>JUL Adapter</a></li>
<li><a href="../log4j-to-slf4j/index.html" title="Log4j 2 to SLF4J Adapter"><span class="none"></span>Log4j 2 to SLF4J Adapter</a></li>
<li><a href="../log4j-flume-ng/index.html" title="Apache Flume Appender"><span class="none"></span>Apache Flume Appender</a></li>
<li><a href="../log4j-taglib/index.html" title="Log4j Tag Library"><span class="none"></span>Log4j Tag Library</a></li>
<li><a href="../log4j-jmx-gui/index.html" title="Log4j JMX GUI"><span class="none"></span>Log4j JMX GUI</a></li>
<li><a href="../log4j-web/index.html" title="Log4j Web Application Support"><span class="none"></span>Log4j Web Application Support</a></li>
<li><a href="../log4j-appserver/index.html" title="Log4j Application Server Integration"><span class="none"></span>Log4j Application Server Integration</a></li>
<li><a href="../log4j-couchdb/index.html" title="Log4j CouchDB appender"><span class="none"></span>Log4j CouchDB appender</a></li>
<li><a href="../log4j-mongodb2/index.html" title="Log4j MongoDB2 appender"><span class="none"></span>Log4j MongoDB2 appender</a></li>
<li><a href="../log4j-mongodb3/index.html" title="Log4j MongoDB3 appender"><span class="none"></span>Log4j MongoDB3 appender</a></li>
<li><a href="../log4j-cassandra/index.html" title="Log4j Cassandra appender"><span class="none"></span>Log4j Cassandra appender</a></li>
<li><a href="../log4j-iostreams/index.html" title="Log4j IO Streams"><span class="none"></span>Log4j IO Streams</a></li>
<li><a href="../log4j-liquibase/index.html" title="Log4j Liquibase Binding"><span class="none"></span>Log4j Liquibase Binding</a></li>
<li><a href="../log4j-docker/index.html" title="Log4j Docker Support"><span class="none"></span>Log4j Docker Support</a></li>
<li><a href="../log4j-spring-cloud-config/log4j-spring-cloud-config-client/index.html" title="Log4j Spring Cloud Config Client"><span class="none"></span>Log4j Spring Cloud Config Client</a></li>
<li class="nav-header"><img class="imageLink" src="../img/glyphicons/info.png" alt="Project Information" border="0"/> Project Information</li>
<li><a href="../dependency-convergence.html" title="Dependency Convergence"><span class="none"></span>Dependency Convergence</a></li>
<li><a href="../dependency-management.html" title="Dependency Management"><span class="none"></span>Dependency Management</a></li>
<li><a href="../team-list.html" title="Project Team"><span class="none"></span>Project Team</a></li>
<li><a href="../mail-lists.html" title="Mailing Lists"><span class="none"></span>Mailing Lists</a></li>
<li><a href="../issue-tracking.html" title="Issue Tracking"><span class="none"></span>Issue Tracking</a></li>
<li><a href="../license.html" title="Project License"><span class="none"></span>Project License</a></li>
<li><a href="../source-repository.html" title="Source Repository"><span class="none"></span>Source Repository</a></li>
<li><a href="../project-summary.html" title="Project Summary"><span class="none"></span>Project Summary</a></li>
<li class="nav-header"><img class="imageLink" src="../img/glyphicons/layers.png" alt="Project Reports" border="0"/> Project Reports</li>
<li><a href="../changes-report.html" title="Changes Report"><span class="none"></span>Changes Report</a></li>
<li><a href="../jira-report.html" title="JIRA Report"><span class="none"></span>JIRA Report</a></li>
<li><a href="../rat-report.html" title="RAT Report"><span class="none"></span>RAT Report</a></li>
</ul>
</nav>
<div class="well sidebar-nav">
<hr />
<div id="poweredBy">
<div class="clear"></div>
<div class="clear"></div>
<div class="clear"></div>
<a href="http://maven.apache.org/" title="Built by Maven" class="poweredBy"><img class="builtBy" alt="Built by Maven" src="../images/logos/maven-feather.png" /></a>
</div>
</div>
</header>
<main id="bodyColumn" class="span10" >
<section>
<h2><a name="Programmatic_Configuration"></a>Programmatic Configuration</h2>
<p>
Log4j 2 provides a few ways for applications to create their own programmatic configuration:
</p>
<ul>
<li>Specify a custom ConfigurationFactory to start Log4j with a programmatic configuration</li>
<li>Use the Configurator to replace the configuration after Log4j started</li>
<li>Initialize Log4j with a combination of a configuration file and programmatic configuration</li>
<li>Modify the current Configuration after initialization</li>
</ul>
<a name="ConfigurationBuilder"></a>
<section>
<h3><a name="The_ConfigurationBuilder_API"></a>The ConfigurationBuilder API</h3>
<p>
Starting with release 2.4, Log4j provides a ConfigurationBuilder and a set of component builders that
allow a Configuration to be created fairly easily.
Actual configuration objects like LoggerConfig or Appender can be unwieldy; they require a lot
of knowledge about Log4j internals which makes them difficult to work with if all you want is to
create a Configuration.
</p>
<p>
The new ConfigurationBuilder API (in the org.apache.logging.log4j.core.config.builder.api package)
allows users to create Configurations in code by constructing component <i>definitions</i>.
There is no need to work directly with actual configuration objects.
Component definitions are added to the ConfigurationBuilder, and once all the definitions have
been collected all the actual configuration objects (like Loggers and Appenders) are constructed.
</p>
<p>
ConfigurationBuilder has convenience methods for the base components that can be configured such as
Loggers, Appenders, Filter, Properties, etc.
However, Log4j 2's plugin mechanism means that users can create any number of custom components.
As a trade-off, the ConfigurationBuilder API provides only a limited number of &quot;strongly typed&quot;
convenience methods like newLogger(), newLayout() etc.
The generic builder.newComponent() method can be used if no convenience method exists
for the component you want to configure.
</p>
<p>
For example, the builder does not know what sub-components can be configured on specific components
such as the RollingFileAppender vs. the RoutingAppender. To specify a triggering policy on a
RollingFileAppender you would use builder.newComponent().
</p>
<p>
Examples of using the ConfigurationBuilder API are in the sections that follow.
</p>
</section>
<a name="ConfigurationFactory"></a>
<section>
<h3><a name="Understanding_ConfigurationFactory"></a>Understanding ConfigurationFactory</h3>
<p>
During initialization, Log4j 2 will search for available <a href="extending.html#ConfigurationFactory">ConfigurationFactories</a>
and then select the one to use. The
selected ConfigurationFactory creates the Configuration that Log4j will use. Here is how Log4j finds
the available ConfigurationFactories:
</p>
<ol style="list-style-type: decimal">
<li>A system property named log4j2.configurationFactory can be set with the name of the ConfigurationFactory to be used.</li>
<li>ConfigurationFactory.setConfigurationFactory(ConfigurationFactory) can be called with the instance of the
ConfigurationFactory to be used. This must be called before any other calls to Log4j.</li>
<li>A ConfigurationFactory implementation can be added to the classpath and configured as a plugin
in the &quot;ConfigurationFactory&quot; category.
The Order annotation can be used to specify the relative priority when multiple applicable
ConfigurationFactories are found.</li>
</ol>
<p>
ConfigurationFactories have the concept of &quot;supported types&quot;, which basically maps to the
file extension of the configuration file that the ConfigurationFactory can handle.
If a configuration file location is specified, ConfigurationFactories whose supported type
does not include &quot;*&quot; or the matching file extension will not be used.
</p>
</section>
<a name="Example"></a>
<section>
<h3><a name="Initialize_Log4j_Using_ConfigurationBuilder_with_a_Custom_ConfigurationFactory"></a>Initialize Log4j Using ConfigurationBuilder with a Custom ConfigurationFactory</h3>
<p>
One way to programmatically configure Log4j 2 is to create a custom ConfigurationFactory
that uses the <a href="#ConfigurationBuilder">ConfigurationBuilder</a> to create a Configuration.
The below example overrides the getConfiguration() method to return a
Configuration created by the ConfigurationBuilder.
This will cause the Configuration to automatically be hooked into Log4j when the LoggerContext is created.
In the example below, because it specifies a supported type of &quot;*&quot; it will override any configuration files provided.
</p>
<div>
<pre class="prettyprint linenum">
@Plugin(name = &quot;CustomConfigurationFactory&quot;, category = ConfigurationFactory.CATEGORY)
@Order(50)
public class CustomConfigurationFactory extends ConfigurationFactory {
static Configuration createConfiguration(final String name, ConfigurationBuilder&lt;BuiltConfiguration&gt; builder) {
builder.setConfigurationName(name);
builder.setStatusLevel(Level.ERROR);
builder.add(builder.newFilter(&quot;ThresholdFilter&quot;, Filter.Result.ACCEPT, Filter.Result.NEUTRAL).
addAttribute(&quot;level&quot;, Level.DEBUG));
AppenderComponentBuilder appenderBuilder = builder.newAppender(&quot;Stdout&quot;, &quot;CONSOLE&quot;).
addAttribute(&quot;target&quot;, ConsoleAppender.Target.SYSTEM_OUT);
appenderBuilder.add(builder.newLayout(&quot;PatternLayout&quot;).
addAttribute(&quot;pattern&quot;, &quot;%d [%t] %-5level: %msg%n%throwable&quot;));
appenderBuilder.add(builder.newFilter(&quot;MarkerFilter&quot;, Filter.Result.DENY,
Filter.Result.NEUTRAL).addAttribute(&quot;marker&quot;, &quot;FLOW&quot;));
builder.add(appenderBuilder);
builder.add(builder.newLogger(&quot;org.apache.logging.log4j&quot;, Level.DEBUG).
add(builder.newAppenderRef(&quot;Stdout&quot;)).
addAttribute(&quot;additivity&quot;, false));
builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef(&quot;Stdout&quot;)));
return builder.build();
}
@Override
public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
return getConfiguration(loggerContext, source.toString(), null);
}
@Override
public Configuration getConfiguration(final LoggerContext loggerContext, final String name, final URI configLocation) {
ConfigurationBuilder&lt;BuiltConfiguration&gt; builder = newConfigurationBuilder();
return createConfiguration(name, builder);
}
@Override
protected String[] getSupportedTypes() {
return new String[] {&quot;*&quot;};
}
}</pre></div>
<p>
As of version 2.7, the ConfigurationFactory.getConfiguration() methods take an
additional LoggerContext parameter.
</p>
</section>
<a name="Configurator"></a>
<section>
<h3><a name="Reconfigure_Log4j_Using_ConfigurationBuilder_with_the_Configurator"></a>Reconfigure Log4j Using ConfigurationBuilder with the Configurator</h3>
<p>
An alternative to a custom ConfigurationFactory is to configure with the Configurator.
Once a Configuration object has been constructed, it can be passed to one of the
Configurator.initialize methods to set up the Log4j configuration.
</p>
<p>
Using the Configurator in this manner allows the application control over when Log4j is initialized.
However, should any logging be attempted before Configurator.initialize() is called then the
default configuration will be used for those log events.
</p>
<div>
<pre class="prettyprint linenum">
ConfigurationBuilder&lt;BuiltConfiguration&gt; builder = ConfigurationBuilderFactory.newConfigurationBuilder();
builder.setStatusLevel(Level.ERROR);
builder.setConfigurationName(&quot;BuilderTest&quot;);
builder.add(builder.newFilter(&quot;ThresholdFilter&quot;, Filter.Result.ACCEPT, Filter.Result.NEUTRAL)
.addAttribute(&quot;level&quot;, Level.DEBUG));
AppenderComponentBuilder appenderBuilder = builder.newAppender(&quot;Stdout&quot;, &quot;CONSOLE&quot;).addAttribute(&quot;target&quot;,
ConsoleAppender.Target.SYSTEM_OUT);
appenderBuilder.add(builder.newLayout(&quot;PatternLayout&quot;)
.addAttribute(&quot;pattern&quot;, &quot;%d [%t] %-5level: %msg%n%throwable&quot;));
appenderBuilder.add(builder.newFilter(&quot;MarkerFilter&quot;, Filter.Result.DENY, Filter.Result.NEUTRAL)
.addAttribute(&quot;marker&quot;, &quot;FLOW&quot;));
builder.add(appenderBuilder);
builder.add(builder.newLogger(&quot;org.apache.logging.log4j&quot;, Level.DEBUG)
.add(builder.newAppenderRef(&quot;Stdout&quot;)).addAttribute(&quot;additivity&quot;, false));
builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef(&quot;Stdout&quot;)));
ctx = Configurator.initialize(builder.build());
</pre></div>
<p>This example shows how to create a configuration that includes a RollingFileAppender.</p>
<div>
<pre class="prettyprint linenum">
ConfigurationBuilder&lt; BuiltConfiguration &gt; builder = ConfigurationBuilderFactory.newConfigurationBuilder();
builder.setStatusLevel( Level.ERROR);
builder.setConfigurationName(&quot;RollingBuilder&quot;);
// create a console appender
AppenderComponentBuilder appenderBuilder = builder.newAppender(&quot;Stdout&quot;, &quot;CONSOLE&quot;).addAttribute(&quot;target&quot;,
ConsoleAppender.Target.SYSTEM_OUT);
appenderBuilder.add(builder.newLayout(&quot;PatternLayout&quot;)
.addAttribute(&quot;pattern&quot;, &quot;%d [%t] %-5level: %msg%n%throwable&quot;));
builder.add( appenderBuilder );
// create a rolling file appender
LayoutComponentBuilder layoutBuilder = builder.newLayout(&quot;PatternLayout&quot;)
.addAttribute(&quot;pattern&quot;, &quot;%d [%t] %-5level: %msg%n&quot;);
ComponentBuilder triggeringPolicy = builder.newComponent(&quot;Policies&quot;)
.addComponent(builder.newComponent(&quot;CronTriggeringPolicy&quot;).addAttribute(&quot;schedule&quot;, &quot;0 0 0 * * ?&quot;))
.addComponent(builder.newComponent(&quot;SizeBasedTriggeringPolicy&quot;).addAttribute(&quot;size&quot;, &quot;100M&quot;));
appenderBuilder = builder.newAppender(&quot;rolling&quot;, &quot;RollingFile&quot;)
.addAttribute(&quot;fileName&quot;, &quot;target/rolling.log&quot;)
.addAttribute(&quot;filePattern&quot;, &quot;target/archive/rolling-%d{MM-dd-yy}.log.gz&quot;)
.add(layoutBuilder)
.addComponent(triggeringPolicy);
builder.add(appenderBuilder);
// create the new logger
builder.add( builder.newLogger( &quot;TestLogger&quot;, Level.DEBUG )
.add( builder.newAppenderRef( &quot;rolling&quot; ) )
.addAttribute( &quot;additivity&quot;, false ) );
builder.add( builder.newRootLogger( Level.DEBUG )
.add( builder.newAppenderRef( &quot;rolling&quot; ) ) );
LoggerContext ctx = Configurator.initialize(builder.build());
</pre></div>
</section>
<a name="Hybrid"></a>
<section>
<h3><a name="Initialize_Log4j_by_Combining_Configuration_File_with_Programmatic_Configuration"></a>Initialize Log4j by Combining Configuration File with Programmatic Configuration</h3>
<p>
Sometimes you want to configure with a configuration file but do some additional programmatic
configuration. A possible use case might be that you want to allow for a flexible configuration using XML
but at the same time make sure there are a few configuration elements that are always present that can't be removed.
</p>
<p>
The easiest way to achieve this is to extend one of the standard Configuration classes
(XMLConfiguration, JSONConfiguration) and then create a new ConfigurationFactory for the extended class.
After the standard configuration completes the custom configuration can be added to it.
</p>
<p>
The example below shows how to extend XMLConfiguration to manually add an Appender and a LoggerConfig
to the configuration.
</p>
<div>
<pre class="prettyprint linenums">
@Plugin(name = &quot;MyXMLConfigurationFactory&quot;, category = &quot;ConfigurationFactory&quot;)
@Order(10)
public class MyXMLConfigurationFactory extends ConfigurationFactory {
/**
* Valid file extensions for XML files.
*/
public static final String[] SUFFIXES = new String[] {&quot;.xml&quot;, &quot;*&quot;};
/**
* Return the Configuration.
* @param source The InputSource.
* @return The Configuration.
*/
public Configuration getConfiguration(InputSource source) {
return new MyXMLConfiguration(source, configFile);
}
/**
* Returns the file suffixes for XML files.
* @return An array of File extensions.
*/
public String[] getSupportedTypes() {
return SUFFIXES;
}
}
public class MyXMLConfiguration extends XMLConfiguration {
public MyXMLConfiguration(final ConfigurationFactory.ConfigurationSource configSource) {
super(configSource);
}
@Override
protected void doConfigure() {
super.doConfigure();
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Layout layout = PatternLayout.createLayout(PatternLayout.SIMPLE_CONVERSION_PATTERN, config, null,
null,null, null);
final Appender appender = FileAppender.createAppender(&quot;target/test.log&quot;, &quot;false&quot;, &quot;false&quot;, &quot;File&quot;, &quot;true&quot;,
&quot;false&quot;, &quot;false&quot;, &quot;4000&quot;, layout, null, &quot;false&quot;, null, config);
appender.start();
addAppender(appender);
LoggerConfig loggerConfig = LoggerConfig.createLogger(&quot;false&quot;, &quot;info&quot;, &quot;org.apache.logging.log4j&quot;,
&quot;true&quot;, refs, null, config, null );
loggerConfig.addAppender(appender, null, null);
addLogger(&quot;org.apache.logging.log4j&quot;, loggerConfig);
}
}</pre></div>
</section>
<a name="AddingToCurrent"></a>
<section>
<h3><a name="Programmatically_Modifying_the_Current_Configuration_after_Initialization"></a>Programmatically Modifying the Current Configuration after Initialization</h3>
<p>
Applications sometimes have the need to customize logging separate from the actual configuration.
Log4j allows this although it suffers from a few limitations:
</p>
<ol style="list-style-type: decimal">
<li>If the configuration file is changed the configuration will be reloaded and the manual changes
will be lost.</li>
<li>Modification to the running configuration requires that all the methods being called (addAppender
and addLogger) be synchronized.</li>
</ol>
<p>
As such, the recommended approach for customizing a configuration is to extend one of the standard
Configuration classes, override the setup method to first do super.setup() and then add the custom
Appenders, Filters and LoggerConfigs to the configuration before it is registered for use.
</p>
<p>
The following example adds an Appender and a new LoggerConfig using that Appender to the current
configuration.
</p>
<div>
<pre class="prettyprint linenums">
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
Layout layout = PatternLayout.createLayout(PatternLayout.SIMPLE_CONVERSION_PATTERN, config, null,
null,null, null);
Appender appender = FileAppender.createAppender(&quot;target/test.log&quot;, &quot;false&quot;, &quot;false&quot;, &quot;File&quot;, &quot;true&quot;,
&quot;false&quot;, &quot;false&quot;, &quot;4000&quot;, layout, null, &quot;false&quot;, null, config);
appender.start();
config.addAppender(appender);
AppenderRef ref = AppenderRef.createAppenderRef(&quot;File&quot;, null, null);
AppenderRef[] refs = new AppenderRef[] {ref};
LoggerConfig loggerConfig = LoggerConfig.createLogger(&quot;false&quot;, &quot;info&quot;, &quot;org.apache.logging.log4j&quot;,
&quot;true&quot;, refs, null, config, null );
loggerConfig.addAppender(appender, null, null);
config.addLogger(&quot;org.apache.logging.log4j&quot;, loggerConfig);
ctx.updateLoggers();
}</pre></div>
</section>
<a name="AppendingToWritersAndOutputStreams"></a>
<section>
<h3><a name="Appending_Log_Events_to_Writers_and_OutputStreams_Programmatically"></a>Appending Log Events to Writers and OutputStreams Programmatically</h3>
<p>
Log4j 2.5 provides facilities to append log events to Writers and OutputStreams. For example, this
provides simple integration for JDBC Driver implementors that use Log4j internally and still want
to support the JDBC APIs CommonDataSource.setLogWriter(PrintWriter),
java.sql.DriverManager.setLogWriter(PrintWriter), and
java.sql.DriverManager.setLogStream(PrintStream).
</p>
<p>
Given any Writer, like a PrintWriter, you tell Log4j to append events to
that writer by creating a WriterAppender and updating the Log4j configuration:
</p>
<div>
<pre class="prettyprint linenums">
void addAppender(final Writer writer, final String writerName) {
final LoggerContext context = LoggerContext.getContext(false);
final Configuration config = context.getConfiguration();
final PatternLayout layout = PatternLayout.createDefaultLayout(config);
final Appender appender = WriterAppender.createAppender(layout, null, writer, writerName, false, true);
appender.start();
config.addAppender(appender);
updateLoggers(appender, config);
}
private void updateLoggers(final Appender appender, final Configuration config) {
final Level level = null;
final Filter filter = null;
for (final LoggerConfig loggerConfig : config.getLoggers().values()) {
loggerConfig.addAppender(appender, level, filter);
}
config.getRootLogger().addAppender(appender, level, filter);
}</pre></div>
<p>
You can achieve the same effect with an OutputStream, like a PrintStream:
</p>
<div>
<pre class="prettyprint linenums">
void addAppender(final OutputStream outputStream, final String outputStreamName) {
final LoggerContext context = LoggerContext.getContext(false);
final Configuration config = context.getConfiguration();
final PatternLayout layout = PatternLayout.createDefaultLayout(config);
final Appender appender = OutputStreamAppender.createAppender(layout, null, outputStream, outputStreamName, false, true);
appender.start();
config.addAppender(appender);
updateLoggers(appender, config);
}</pre></div>
</section>
<p>
The difference is the use of OutputStreamAppender instead of WriterAppender.
</p>
</section>
</main>
</div>
</div>
<hr/>
<footer>
<div class="container-fluid">
<div class="row-fluid">
<p align="center">Copyright &copy; 1999-2019 <a class="external" href="http://www.apache.org">The Apache Software Foundation</a>. All Rights Reserved.<br>
Apache Logging, Apache Log4j, Log4j, Apache, the Apache feather logo, and the Apache Logging project logo are trademarks of The Apache Software Foundation.</p>
</div>
</div>
</footer>
</body>
</html>