"Fossies" - the Fresh Open Source Software Archive 
Member "apache-log4j-2.12.4-src/src/site/xdoc/manual/appenders.xml" (28 Dec 2021, 258713 Bytes) of package /linux/misc/apache-log4j-2.12.4-src.tar.gz:
As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) XML source code syntax highlighting (style:
standard) with prefixed line numbers.
Alternatively you can here
view or
download the uninterpreted source code file.
See also the latest
Fossies "Diffs" side-by-side code changes report for "appenders.xml":
2.12.3_vs_2.12.4.
1 <?xml version="1.0"?>
2 <!--
3 Licensed to the Apache Software Foundation (ASF) under one or more
4 contributor license agreements. See the NOTICE file distributed with
5 this work for additional information regarding copyright ownership.
6 The ASF licenses this file to You under the Apache License, Version 2.0
7 (the "License"); you may not use this file except in compliance with
8 the License. You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17 -->
18
19 <document xmlns="http://maven.apache.org/XDOC/2.0"
20 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
21 xsi:schemaLocation="http://maven.apache.org/XDOC/2.0 http://maven.apache.org/xsd/xdoc-2.0.xsd">
22 <properties>
23 <title>Log4j 2 Appenders</title>
24 <author email="rgoers@apache.org">Ralph Goers</author>
25 <author email="ggrgeory@apache.org">Gary Gregory</author>
26 <author email="nickwilliams@apache.org">Nick Williams</author>
27 <author email="mattsicker@apache.org">Matt SIcker</author>
28 </properties>
29
30 <body>
31 <section name="Appenders">
32 <p>
33 Appenders are responsible for delivering LogEvents to their destination. Every Appender must
34 implement the <a href="../log4j-core/apidocs/org/apache/logging/log4j/core/Appender.html">Appender</a>
35 interface. Most Appenders will extend
36 <a href="../log4j-core/apidocs/org/apache/logging/log4j/core/appender/AbstractAppender.html">AbstractAppender</a>
37 which adds <a href="../log4j-core/apidocs/org/apache/logging/log4j/core/LifeCycle.html">Lifecycle</a>
38 and <a href="../log4j-core/apidocs/org/apache/logging/log4j/core/filter/Filterable.html">Filterable</a>
39 support. Lifecycle allows components to finish initialization after configuration has completed and to
40 perform cleanup during shutdown. Filterable allows the component to have Filters attached to it which are
41 evaluated during event processing.
42 </p>
43 <p>
44 Appenders usually are only responsible for writing the event data to the target destination. In most cases
45 they delegate responsibility for formatting the event to a <a href="layouts.html">layout</a>. Some
46 appenders wrap other appenders so that they can modify the LogEvent, handle a failure in an Appender,
47 route the event to a subordinate Appender based on advanced Filter criteria or provide similar functionality
48 that does not directly format the event for viewing.
49 </p>
50 <p>
51 Appenders always have a name so that they can be referenced from Loggers.
52 </p>
53 <p>
54 In the tables below, the "Type" column corresponds to the Java type expected. For non-JDK classes, these
55 should usually be in <a href="../log4j-core/apidocs/index.html">Log4j Core</a> unless otherwise noted.
56 </p>
57 <a name="AsyncAppender"/>
58 <subsection name="AsyncAppender">
59 <p>The AsyncAppender accepts references to other Appenders and causes LogEvents to be written to them
60 on a separate Thread. Note that exceptions while writing to those Appenders will be hidden from
61 the application. The AsyncAppender should be configured after the appenders it references to allow it
62 to shut down properly.</p>
63 <p>
64 By default, AsyncAppender uses
65 <a class="javadoc" href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ArrayBlockingQueue.html">java.util.concurrent.ArrayBlockingQueue</a>
66 which does not require any external libraries. Note that multi-threaded applications should exercise care
67 when using this appender as such: the blocking queue is susceptible to lock contention and our
68 <a href="../performance.html#asyncLogging">tests showed</a>
69 performance may become worse when more threads are logging concurrently.
70 Consider using <a href="async.html">lock-free Async Loggers</a> for optimal performance.
71 </p>
72 <table>
73 <caption align="top">AsyncAppender Parameters</caption>
74 <tr>
75 <th>Parameter Name</th>
76 <th>Type</th>
77 <th>Description</th>
78 </tr>
79 <tr>
80 <td>AppenderRef</td>
81 <td>String</td>
82 <td>The name of the Appenders to invoke asynchronously. Multiple AppenderRef
83 elements can be configured.</td>
84 </tr>
85 <tr>
86 <td>blocking</td>
87 <td>boolean</td>
88 <td>If true, the appender will wait until there are free slots in the queue. If false, the event
89 will be written to the error appender if the queue is full. The default is true.</td>
90 </tr>
91 <tr>
92 <td>shutdownTimeout</td>
93 <td>integer</td>
94 <td>How many milliseconds the Appender should wait to flush outstanding log events in the queue
95 on shutdown. The default is zero which means to wait forever.</td>
96 </tr>
97 <tr>
98 <td>bufferSize</td>
99 <td>integer</td>
100 <td>Specifies the maximum number of events that can be queued. The default is 1024. Note that when using a
101 disruptor-style <tt>BlockingQueue</tt>, this buffer size must be a power of 2.
102 <p>
103 When the application is logging faster than the underlying appender can keep up with
104 for a long enough time to fill up the queue, the behavious is determined by the
105 <a href="../log4j-core/apidocs/org/apache/logging/log4j/core/async/AsyncQueueFullPolicy.html">AsyncQueueFullPolicy</a>.
106 </p>
107 </td>
108 </tr>
109 <tr>
110 <td>errorRef</td>
111 <td>String</td>
112 <td>The name of the Appender to invoke if none of the appenders can be called, either due to errors
113 in the appenders or because the queue is full. If not specified then errors will be ignored.</td>
114 </tr>
115 <tr>
116 <td>filter</td>
117 <td>Filter</td>
118 <td>A Filter to determine if the event should be handled by this Appender. More than one Filter
119 may be used by using a CompositeFilter.</td>
120 </tr>
121 <tr>
122 <td>name</td>
123 <td>String</td>
124 <td>The name of the Appender.</td>
125 </tr>
126 <tr>
127 <td>ignoreExceptions</td>
128 <td>boolean</td>
129 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
130 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
131 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
132 <a href="#FailoverAppender">FailoverAppender</a>.</td>
133 </tr>
134 <tr>
135 <td>includeLocation</td>
136 <td>boolean</td>
137 <td>Extracting location is an expensive operation (it can make
138 logging 5 - 20 times slower). To improve performance, location is
139 not included by default when adding a log event to the queue.
140 You can change this by setting includeLocation="true".</td>
141 </tr>
142 <tr>
143 <td>BlockingQueueFactory</td>
144 <td>BlockingQueueFactory</td>
145 <td>This element overrides what type of <tt>BlockingQueue</tt> to use. See
146 <a href="#BlockingQueueFactory">below documentation</a> for more details.</td>
147 </tr>
148 </table>
149 <p>
150 There are also a few system properties that can be used to maintain application throughput even when
151 the underlying appender cannot keep up with the logging rate and the queue is filling up.
152 See the details for system properties
153 <a href="configuration.html#log4j2.AsyncQueueFullPolicy"><tt>log4j2.AsyncQueueFullPolicy</tt> and
154 <tt>log4j2.DiscardThreshold</tt></a>.
155 </p>
156 <p>
157 A typical AsyncAppender configuration might look like:
158 </p>
159
160 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
161 <Configuration status="warn" name="MyApp" packages="">
162 <Appenders>
163 <File name="MyFile" fileName="logs/app.log">
164 <PatternLayout>
165 <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
166 </PatternLayout>
167 </File>
168 <Async name="Async">
169 <AppenderRef ref="MyFile"/>
170 </Async>
171 </Appenders>
172 <Loggers>
173 <Root level="error">
174 <AppenderRef ref="Async"/>
175 </Root>
176 </Loggers>
177 </Configuration>]]></pre>
178 <p>
179 <a name="BlockingQueueFactory"/>
180 Starting in Log4j 2.7, a custom implementation of <tt>BlockingQueue</tt> or <tt>TransferQueue</tt> can be
181 specified using a
182 <a class="javadoc" href="../log4j-core/apidocs/org/apache/logging/log4j/core/async/BlockingQueueFactory.html">BlockingQueueFactory</a>
183 plugin. To override the default <tt>BlockingQueueFactory</tt>, specify the plugin inside an
184 <code><![CDATA[<Async/>]]></code> element like so:
185 </p>
186 <pre class="prettyprint linenums"><![CDATA[
187 <Configuration name="LinkedTransferQueueExample">
188 <Appenders>
189 <List name="List"/>
190 <Async name="Async" bufferSize="262144">
191 <AppenderRef ref="List"/>
192 <LinkedTransferQueue/>
193 </Async>
194 </Appenders>
195 <Loggers>
196 <Root>
197 <AppenderRef ref="Async"/>
198 </Root>
199 </Loggers>
200 </Configuration>]]></pre>
201 <p>
202 Log4j ships with the following implementations:
203 </p>
204 <table>
205 <caption align="top">BlockingQueueFactory Implementations</caption>
206 <tr>
207 <th>Plugin Name</th>
208 <th>Description</th>
209 </tr>
210 <tr>
211 <td>ArrayBlockingQueue</td>
212 <td>
213 This is the default implementation that uses
214 <a class="javadoc" href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ArrayBlockingQueue.html">ArrayBlockingQueue</a>.
215 </td>
216 </tr>
217 <tr>
218 <td>DisruptorBlockingQueue</td>
219 <td>
220 This uses the <a href="https://github.com/conversant/disruptor">Conversant Disruptor</a> implementation
221 of <tt>BlockingQueue</tt>. This plugin takes a single optional attribute, <tt>spinPolicy</tt>, which
222 corresponds to
223 <!-- TODO: this needs performance charts and links added -->
224 </td>
225 </tr>
226 <tr>
227 <td>JCToolsBlockingQueue</td>
228 <td>
229 This uses <a href="https://jctools.github.io/JCTools/">JCTools</a>, specifically the
230 <abbr title="multiple producer single consumer">MPSC</abbr> bounded lock-free queue.
231 <!-- TODO: this need performance charts and links added -->
232 </td>
233 </tr>
234 <tr>
235 <td>LinkedTransferQueue</td>
236 <td>
237 This uses the new in Java 7 implementation
238 <a class="javadoc" href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/LinkedTransferQueue.html">LinkedTransferQueue</a>.
239 Note that this queue does not use the <tt>bufferSize</tt> configuration attribute from AsyncAppender as
240 <tt>LinkedTransferQueue</tt> does not support a maximum capacity.
241 <!-- TODO: this needs performance charts and links added -->
242 </td>
243 </tr>
244 </table>
245 </subsection>
246 <a name="CassandraAppender"/>
247 <subsection name="CassandraAppender">
248 <p>
249 The CassandraAppender writes its output to an <a href="https://cassandra.apache.org/">Apache Cassandra</a>
250 database. A keyspace and table must be configured ahead of time, and the columns of that table are mapped
251 in a configuration file. Each column can specify either a <a href="layouts.html">StringLayout</a> (e.g., a
252 <a href="layouts.html#PatternLayout">PatternLayout</a>) along with an optional conversion type, or only
253 a conversion type for <code>org.apache.logging.log4j.spi.ThreadContextMap</code> or
254 <code>org.apache.logging.log4j.spi.ThreadContextStack</code> to store the <a href="thread-context.html">MDC or NDC</a>
255 in a map or list column respectively. A conversion type compatible with <code>java.util.Date</code> will
256 use the log event timestamp converted to that type (e.g., use <code>java.util.Date</code> to fill a
257 <code>timestamp</code> column type in Cassandra).
258 </p>
259 <table>
260 <caption align="top">CassandraAppender Parameters</caption>
261 <tr>
262 <th>Parameter Name</th>
263 <th>Type</th>
264 <th>Description</th>
265 </tr>
266 <tr>
267 <td>batched</td>
268 <td>boolean</td>
269 <td>Whether or not to use batch statements to write log messages to Cassandra. By default, this is <code>false</code>.</td>
270 </tr>
271 <tr>
272 <td>batchType</td>
273 <td><a href="http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/BatchStatement.Type.html">BatchStatement.Type</a></td>
274 <td>The batch type to use when using batched writes. By default, this is <code>LOGGED</code>.</td>
275 </tr>
276 <tr>
277 <td>bufferSize</td>
278 <td>int</td>
279 <td>The number of log messages to buffer or batch before writing. By default, no buffering is done.</td>
280 </tr>
281 <tr>
282 <td>clusterName</td>
283 <td>String</td>
284 <td>The name of the Cassandra cluster to connect to.</td>
285 </tr>
286 <tr>
287 <td>columns</td>
288 <td>ColumnMapping[]</td>
289 <td>A list of column mapping configurations. Each column must specify a column name. Each column can
290 have a conversion type specified by its fully qualified class name. By default, the conversion type is
291 <code>String</code>. If the configured type is assignment-compatible with
292 <a class="javadoc" href="../log4j-api/apidocs/org/apache/logging/log4j/util/ReadOnlyStringMap.html">ReadOnlyStringMap</a>
293 /
294 <a class="javadoc" href="../log4j-api/apidocs/org/apache/logging/log4j/spi/ThreadContextMap.html">ThreadContextMap</a>
295 or
296 <a class="javadoc" href="../log4j-api/apidocs/org/apache/logging/log4j/spi/ThreadContextStack.html">ThreadContextStack</a>,
297 then that column will be populated with the MDC or NDC respectively. If the configured type is
298 assignment-compatible with <code>java.util.Date</code>, then the log timestamp will be converted to
299 that configured date type. If a <code>literal</code> attribute is given, then its value will be used as
300 is in the <code>INSERT</code> query without any escaping. Otherwise, the layout or pattern specified
301 will be converted into the configured type and stored in that column.
302 </td>
303 </tr>
304 <tr>
305 <td>contactPoints</td>
306 <td>SocketAddress[]</td>
307 <td>A list of hosts and ports of Cassandra nodes to connect to. These must be valid hostnames or IP
308 addresses. By default, if a port is not specified for a host or it is set to 0, then the default
309 Cassandra port of 9042 will be used. By default, <code>localhost:9042</code> will be used.</td>
310 </tr>
311 <tr>
312 <td>filter</td>
313 <td>Filter</td>
314 <td>A Filter to determine if the event should be handled by this Appender. More than one Filter may be used
315 by using a CompositeFilter.</td>
316 </tr>
317 <tr>
318 <td>ignoreExceptions</td>
319 <td>boolean</td>
320 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
321 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
322 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
323 <a href="#FailoverAppender">FailoverAppender</a>.</td>
324 </tr>
325 <tr>
326 <td>keyspace</td>
327 <td>String</td>
328 <td>The name of the keyspace containing the table that log messages will be written to.</td>
329 </tr>
330 <tr>
331 <td>name</td>
332 <td>String</td>
333 <td>The name of the Appender.</td>
334 </tr>
335 <tr>
336 <td>password</td>
337 <td>String</td>
338 <td>The password to use (along with the username) to connect to Cassandra.</td>
339 </tr>
340 <tr>
341 <td>table</td>
342 <td>String</td>
343 <td>The name of the table to write log messages to.</td>
344 </tr>
345 <tr>
346 <td>useClockForTimestampGenerator</td>
347 <td>boolean</td>
348 <td>Whether or not to use the configured <code>org.apache.logging.log4j.core.util.Clock</code> as a
349 <a class="javadoc" href="http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/TimestampGenerator.html">TimestampGenerator</a>.
350 By default, this is <code>false</code>.</td>
351 </tr>
352 <tr>
353 <td>username</td>
354 <td>String</td>
355 <td>The username to use to connect to Cassandra. By default, no username or password is used.</td>
356 </tr>
357 <tr>
358 <td>useTls</td>
359 <td>boolean</td>
360 <td>Whether or not to use TLS/SSL to connect to Cassandra. This is <code>false</code> by default.</td>
361 </tr>
362 </table>
363 <p>
364 Here is an example CassandraAppender configuration:
365 </p>
366 <pre class="prettyprint linenums"><![CDATA[
367 <Configuration name="CassandraAppenderTest">
368 <Appenders>
369 <Cassandra name="Cassandra" clusterName="Test Cluster" keyspace="test" table="logs" bufferSize="10" batched="true">
370 <SocketAddress host="localhost" port="9042"/>
371 <ColumnMapping name="id" pattern="%uuid{TIME}" type="java.util.UUID"/>
372 <ColumnMapping name="timeid" literal="now()"/>
373 <ColumnMapping name="message" pattern="%message"/>
374 <ColumnMapping name="level" pattern="%level"/>
375 <ColumnMapping name="marker" pattern="%marker"/>
376 <ColumnMapping name="logger" pattern="%logger"/>
377 <ColumnMapping name="timestamp" type="java.util.Date"/>
378 <ColumnMapping name="mdc" type="org.apache.logging.log4j.spi.ThreadContextMap"/>
379 <ColumnMapping name="ndc" type="org.apache.logging.log4j.spi.ThreadContextStack"/>
380 </Cassandra>
381 </Appenders>
382 <Loggers>
383 <Logger name="org.apache.logging.log4j.cassandra" level="DEBUG">
384 <AppenderRef ref="Cassandra"/>
385 </Logger>
386 <Root level="ERROR"/>
387 </Loggers>
388 </Configuration>
389 ]]></pre>
390 <p>
391 This example configuration uses the following table schema:
392 </p>
393 <pre class="prettyprint linenums"><![CDATA[
394 CREATE TABLE logs (
395 id timeuuid PRIMARY KEY,
396 timeid timeuuid,
397 message text,
398 level text,
399 marker text,
400 logger text,
401 timestamp timestamp,
402 mdc map<text,text>,
403 ndc list<text>
404 );
405 ]]></pre>
406 </subsection>
407 <a name="ConsoleAppender"/>
408 <subsection name="ConsoleAppender">
409 <p>
410 As one might expect, the ConsoleAppender writes its output to either System.out or System.err with System.out
411 being the default target. A Layout must be provided to format the LogEvent.
412 </p>
413 <table>
414 <caption align="top">ConsoleAppender Parameters</caption>
415 <tr>
416 <th>Parameter Name</th>
417 <th>Type</th>
418 <th>Description</th>
419 </tr>
420 <tr>
421 <td>filter</td>
422 <td>Filter</td>
423 <td>A Filter to determine if the event should be handled by this Appender. More than one Filter
424 may be used by using a CompositeFilter.</td>
425 </tr>
426 <tr>
427 <td>layout</td>
428 <td>Layout</td>
429 <td>The Layout to use to format the LogEvent. If no layout is supplied the default pattern layout
430 of "%m%n" will be used.</td>
431 </tr>
432 <tr>
433 <td>follow</td>
434 <td>boolean</td>
435 <td>Identifies whether the appender honors reassignments of System.out or System.err
436 via System.setOut or System.setErr made after configuration. Note that the follow
437 attribute cannot be used with Jansi on Windows. Cannot be used with <code>direct</code>.</td>
438 </tr>
439 <tr>
440 <td>direct</td>
441 <td>boolean</td>
442 <td>Write directly to <code>java.io.FileDescriptor</code> and bypass <code>java.lang.System.out/.err</code>.
443 Can give up to 10x performance boost when the output is redirected to file or other process.
444 Cannot be used with Jansi on Windows. Cannot be used with <code>follow</code>. Output will not respect
445 <code>java.lang.System.setOut()/.setErr()</code> and may get intertwined with other output to
446 <code>java.lang.System.out/.err</code> in a multi-threaded application.
447 <i>New since 2.6.2. Be aware that this is a new addition, and it has only been tested with Oracle JVM
448 on Linux and Windows so far.</i></td>
449 </tr>
450 <tr>
451 <td>name</td>
452 <td>String</td>
453 <td>The name of the Appender.</td>
454 </tr>
455 <tr>
456 <td>ignoreExceptions</td>
457 <td>boolean</td>
458 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
459 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
460 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
461 <a href="#FailoverAppender">FailoverAppender</a>.</td>
462 </tr>
463 <tr>
464 <td>target</td>
465 <td>String</td>
466 <td>Either "SYSTEM_OUT" or "SYSTEM_ERR". The default is "SYSTEM_OUT".</td>
467 </tr>
468 </table>
469 <p>
470 A typical Console configuration might look like:
471 </p>
472
473 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
474 <Configuration status="warn" name="MyApp" packages="">
475 <Appenders>
476 <Console name="STDOUT" target="SYSTEM_OUT">
477 <PatternLayout pattern="%m%n"/>
478 </Console>
479 </Appenders>
480 <Loggers>
481 <Root level="error">
482 <AppenderRef ref="STDOUT"/>
483 </Root>
484 </Loggers>
485 </Configuration>]]></pre>
486 </subsection>
487 <a name="FailoverAppender"/>
488 <subsection name="FailoverAppender">
489 <p>The FailoverAppender wraps a set of appenders. If the primary Appender fails the secondary appenders will be
490 tried in order until one succeeds or there are no more secondaries to try.</p>
491 <table>
492 <caption align="top">FailoverAppender Parameters</caption>
493 <tr>
494 <th>Parameter Name</th>
495 <th>Type</th>
496 <th>Description</th>
497 </tr>
498 <tr>
499 <td>filter</td>
500 <td>Filter</td>
501 <td>A Filter to determine if the event should be handled by this Appender. More than one Filter
502 may be used by using a CompositeFilter.</td>
503 </tr>
504 <tr>
505 <td>primary</td>
506 <td>String</td>
507 <td>The name of the primary Appender to use.</td>
508 </tr>
509 <tr>
510 <td>failovers</td>
511 <td>String[]</td>
512 <td>The names of the secondary Appenders to use.</td>
513 </tr>
514
515 <tr>
516 <td>name</td>
517 <td>String</td>
518 <td>The name of the Appender.</td>
519 </tr>
520 <tr>
521 <td>retryIntervalSeconds</td>
522 <td>integer</td>
523 <td>The number of seconds that should pass before retrying the primary Appender. The default is 60.</td>
524 </tr>
525 <tr>
526 <td>ignoreExceptions</td>
527 <td>boolean</td>
528 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
529 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
530 caller, instead.</td>
531 </tr>
532 <tr>
533 <td>target</td>
534 <td>String</td>
535 <td>Either "SYSTEM_OUT" or "SYSTEM_ERR". The default is "SYSTEM_ERR".</td>
536 </tr>
537 </table>
538 <p>
539 A Failover configuration might look like:
540 </p>
541
542 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
543 <Configuration status="warn" name="MyApp" packages="">
544 <Appenders>
545 <RollingFile name="RollingFile" fileName="logs/app.log" filePattern="logs/app-%d{MM-dd-yyyy}.log.gz"
546 ignoreExceptions="false">
547 <PatternLayout>
548 <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
549 </PatternLayout>
550 <TimeBasedTriggeringPolicy />
551 </RollingFile>
552 <Console name="STDOUT" target="SYSTEM_OUT" ignoreExceptions="false">
553 <PatternLayout pattern="%m%n"/>
554 </Console>
555 <Failover name="Failover" primary="RollingFile">
556 <Failovers>
557 <AppenderRef ref="Console"/>
558 </Failovers>
559 </Failover>
560 </Appenders>
561 <Loggers>
562 <Root level="error">
563 <AppenderRef ref="Failover"/>
564 </Root>
565 </Loggers>
566 </Configuration>]]></pre>
567 </subsection>
568 <a name="FileAppender"/>
569 <subsection name="FileAppender">
570 <p>The FileAppender is an OutputStreamAppender that writes to the File named in the fileName parameter. The
571 FileAppender uses a FileManager (which extends OutputStreamManager) to actually perform the file I/O. While
572 FileAppenders from different Configurations cannot be shared, the FileManagers can be if the Manager is
573 accessible. For example, two web applications in a servlet container can have their own configuration and
574 safely write to the same file if Log4j is in a ClassLoader that is common to both of them.</p>
575 <table>
576 <caption align="top">FileAppender Parameters</caption>
577 <tr>
578 <th>Parameter Name</th>
579 <th>Type</th>
580 <th>Description</th>
581 </tr>
582 <tr>
583 <td>append</td>
584 <td>boolean</td>
585 <td>When true - the default, records will be appended to the end of the file. When set to false,
586 the file will be cleared before new records are written.</td>
587 </tr>
588 <tr>
589 <td>bufferedIO</td>
590 <td>boolean</td>
591 <td>When true - the default, records will be written to a buffer and the data will be written to
592 disk when the buffer is full or, if immediateFlush is set, when the record is written.
593 File locking cannot be used with bufferedIO. Performance tests have shown that using buffered I/O
594 significantly improves performance, even if immediateFlush is enabled.</td>
595 </tr>
596 <tr>
597 <td>bufferSize</td>
598 <td>int</td>
599 <td>When bufferedIO is true, this is the buffer size, the default is 8192 bytes.</td>
600 </tr>
601 <tr>
602 <td>createOnDemand</td>
603 <td>boolean</td>
604 <td>The appender creates the file on-demand. The appender only creates the file when a log event
605 passes all filters and is routed to this appender. Defaults to false.</td>
606 </tr>
607 <tr>
608 <td>filter</td>
609 <td>Filter</td>
610 <td>A Filter to determine if the event should be handled by this Appender. More than one Filter
611 may be used by using a CompositeFilter.</td>
612 </tr>
613 <tr>
614 <td>fileName</td>
615 <td>String</td>
616 <td>The name of the file to write to. If the file, or any of its parent directories, do not exist,
617 they will be created.</td>
618 </tr>
619 <tr>
620 <td>immediateFlush</td>
621 <td>boolean</td>
622 <td><p>When set to true - the default, each write will be followed by a flush.
623 This will guarantee the data is written
624 to disk but could impact performance.</p>
625 <p>Flushing after every write is only useful when using this
626 appender with synchronous loggers. Asynchronous loggers and
627 appenders will automatically flush at the end of a batch of events,
628 even if immediateFlush is set to false. This also guarantees
629 the data is written to disk but is more efficient.</p>
630 </td>
631 </tr>
632 <tr>
633 <td>layout</td>
634 <td>Layout</td>
635 <td>The Layout to use to format the LogEvent. If no layout is supplied the default pattern layout
636 of "%m%n" will be used.</td>
637 </tr>
638 <tr>
639 <td>locking</td>
640 <td>boolean</td>
641 <td>When set to true, I/O operations will occur only while the file lock is held allowing FileAppenders
642 in multiple JVMs and potentially multiple hosts to write to the same file simultaneously. This
643 will significantly impact performance so should be used carefully. Furthermore, on many systems
644 the file lock is "advisory" meaning that other applications can perform operations on the file
645 without acquiring a lock. The default value is false.</td>
646 </tr>
647 <tr>
648 <td>name</td>
649 <td>String</td>
650 <td>The name of the Appender.</td>
651 </tr>
652 <tr>
653 <td>ignoreExceptions</td>
654 <td>boolean</td>
655 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
656 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
657 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
658 <a href="#FailoverAppender">FailoverAppender</a>.</td>
659 </tr>
660 <tr>
661 <td>filePermissions</td>
662 <td>String</td>
663 <td><p>File attribute permissions in POSIX format to apply whenever the file is created.</p>
664 <p>Underlying files system shall support <a class="javadoc" href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/PosixFileAttributeView.html">POSIX</a> file attribute view.</p>
665 <p>Examples: rw------- or rw-rw-rw- etc...</p></td>
666 </tr>
667 <tr>
668 <td>fileOwner</td>
669 <td>String</td>
670 <td><p>File owner to define whenever the file is created.</p>
671 <p>Changing file's owner may be restricted for security reason and Operation not permitted IOException thrown.
672 Only processes with an effective user ID equal to the user ID
673 of the file or with appropriate privileges may change the ownership of a file
674 if <a href="http://www.gnu.org/software/libc/manual/html_node/Options-for-Files.html">_POSIX_CHOWN_RESTRICTED</a> is in effect for path.</p>
675 <p>Underlying files system shall support file <a class="javadoc" href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/FileOwnerAttributeView.html">owner</a> attribute view.</p>
676 </td>
677 </tr>
678 <tr>
679 <td>fileGroup</td>
680 <td>String</td>
681 <td><p>File group to define whenever the file is created.</p>
682 <p>Underlying files system shall support <a class="javadoc" href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/PosixFileAttributeView.html">POSIX</a> file attribute view.</p>
683 </td>
684 </tr>
685 </table>
686 <p>
687 Here is a sample File configuration:
688 </p>
689
690 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
691 <Configuration status="warn" name="MyApp" packages="">
692 <Appenders>
693 <File name="MyFile" fileName="logs/app.log">
694 <PatternLayout>
695 <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
696 </PatternLayout>
697 </File>
698 </Appenders>
699 <Loggers>
700 <Root level="error">
701 <AppenderRef ref="MyFile"/>
702 </Root>
703 </Loggers>
704 </Configuration>]]></pre>
705 </subsection>
706 <a name="FlumeAppender"/>
707 <subsection name="FlumeAppender">
708 <p><i>This is an optional component supplied in a separate jar.</i></p>
709 <p><a href="http://flume.apache.org/index.html">Apache Flume</a> is a distributed, reliable,
710 and available system for efficiently collecting, aggregating, and moving large amounts of log data
711 from many different sources to a centralized data store. The FlumeAppender takes LogEvents and sends
712 them to a Flume agent as serialized Avro events for consumption.</p>
713 <p>
714 The Flume Appender supports three modes of operation.
715 </p>
716 <ol>
717 <li>It can act as a remote Flume client which sends Flume events via Avro to a Flume Agent configured
718 with an Avro Source.</li>
719 <li>It can act as an embedded Flume Agent where Flume events pass directly into Flume for processing.</li>
720 <li>It can persist events to a local BerkeleyDB data store and then asynchronously send the events to
721 Flume, similar to the embedded Flume Agent but without most of the Flume dependencies.</li>
722 </ol>
723 <p>
724 Usage as an embedded agent will cause the messages to be directly passed to the Flume Channel and then
725 control will be immediately returned to the application. All interaction with remote agents will occur
726 asynchronously. Setting the "type" attribute to "Embedded" will force the use of the embedded agent. In
727 addition, configuring agent properties in the appender configuration will also cause the embedded agent
728 to be used.
729 </p>
730 <table>
731 <caption align="top">FlumeAppender Parameters</caption>
732 <tr>
733 <th>Parameter Name</th>
734 <th>Type</th>
735 <th>Description</th>
736 </tr>
737 <tr>
738 <td>agents</td>
739 <td>Agent[]</td>
740 <td>An array of Agents to which the logging events should be sent. If more than one agent is specified
741 the first Agent will be the primary and subsequent Agents will be used in the order specified as
742 secondaries should the primary Agent fail. Each Agent definition supplies the Agents host and port.
743 The specification of agents and properties are mutually exclusive. If both are configured an
744 error will result.</td>
745 </tr>
746 <tr>
747 <td>agentRetries</td>
748 <td>integer</td>
749 <td>The number of times the agent should be retried before failing to a secondary. This parameter is
750 ignored when type="persistent" is specified (agents are tried once before failing to the next).</td>
751 </tr>
752 <tr>
753 <td>batchSize</td>
754 <td>integer</td>
755 <td>Specifies the number of events that should be sent as a batch. The default is 1. <i>This
756 parameter only applies to the Flume Appender.</i></td>
757 </tr>
758 <tr>
759 <td>compress</td>
760 <td>boolean</td>
761 <td>When set to true the message body will be compressed using gzip</td>
762 </tr>
763 <tr>
764 <td>connectTimeoutMillis</td>
765 <td>integer</td>
766 <td>The number of milliseconds Flume will wait before timing out the connection.</td>
767 </tr>
768 <tr>
769 <td>dataDir</td>
770 <td>String</td>
771 <td>Directory where the Flume write ahead log should be written. Valid only when embedded is set
772 to true and Agent elements are used instead of Property elements.</td>
773 </tr>
774 <tr>
775 <td>filter</td>
776 <td>Filter</td>
777 <td>A Filter to determine if the event should be handled by this Appender. More than one Filter
778 may be used by using a CompositeFilter.</td>
779 </tr>
780 <tr>
781 <td>eventPrefix</td>
782 <td>String</td>
783 <td>The character string to prepend to each event attribute in order to distinguish it from MDC attributes.
784 The default is an empty string.</td>
785 </tr>
786 <tr>
787 <td>flumeEventFactory</td>
788 <td>FlumeEventFactory</td>
789 <td>Factory that generates the Flume events from Log4j events. The default factory is the
790 FlumeAvroAppender itself.</td>
791 </tr>
792 <tr>
793 <td>layout</td>
794 <td>Layout</td>
795 <td>The Layout to use to format the LogEvent. If no layout is specified RFC5424Layout will be used.</td>
796 </tr>
797 <tr>
798 <td>lockTimeoutRetries</td>
799 <td>integer</td>
800 <td>The number of times to retry if a LockConflictException occurs while writing to Berkeley DB. The
801 default is 5.</td>
802 </tr>
803 <tr>
804 <td>maxDelayMillis</td>
805 <td>integer</td>
806 <td>The maximum number of milliseconds to wait for batchSize events before publishing the batch.</td>
807 </tr>
808 <tr>
809 <td>mdcExcludes</td>
810 <td>String</td>
811 <td>A comma separated list of mdc keys that should be excluded from the FlumeEvent. This is mutually
812 exclusive with the mdcIncludes attribute.</td>
813 </tr>
814 <tr>
815 <td>mdcIncludes</td>
816 <td>String</td>
817 <td>A comma separated list of mdc keys that should be included in the FlumeEvent. Any keys in the MDC
818 not found in the list will be excluded. This option is mutually exclusive with the mdcExcludes
819 attribute.</td>
820 </tr>
821 <tr>
822 <td>mdcRequired</td>
823 <td>String</td>
824 <td>A comma separated list of mdc keys that must be present in the MDC. If a key is not present a
825 LoggingException will be thrown.</td>
826 </tr>
827 <tr>
828 <td>mdcPrefix</td>
829 <td>String</td>
830 <td>A string that should be prepended to each MDC key in order to distinguish it from event attributes.
831 The default string is "mdc:".</td>
832 </tr>
833 <tr>
834 <td>name</td>
835 <td>String</td>
836 <td>The name of the Appender.</td>
837 </tr>
838 <tr>
839 <td>properties</td>
840 <td>Property[]</td>
841 <td><p>One or more Property elements that are used to configure the Flume Agent. The properties must be
842 configured without the agent name (the appender name is used for this) and no sources can be
843 configured. Interceptors can be specified for the source using "sources.log4j-source.interceptors".
844 All other Flume configuration properties are allowed. Specifying both Agent and Property
845 elements will result in an error.</p>
846 <p>When used to configure in Persistent mode the valid properties are:</p>
847 <ol>
848 <li>"keyProvider" to specify the name of the plugin to provide the secret key for encryption.</li>
849 </ol>
850 </td>
851 </tr>
852 <tr>
853 <td>requestTimeoutMillis</td>
854 <td>integer</td>
855 <td>The number of milliseconds Flume will wait before timing out the request.</td>
856 </tr>
857 <tr>
858 <td>ignoreExceptions</td>
859 <td>boolean</td>
860 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
861 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
862 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
863 <a href="#FailoverAppender">FailoverAppender</a>.</td>
864 </tr>
865 <tr>
866 <td>type</td>
867 <td>enumeration</td>
868 <td>One of "Avro", "Embedded", or "Persistent" to indicate which variation of the Appender is desired.</td>
869 </tr>
870 </table>
871 <p>
872 A sample FlumeAppender configuration that is configured with a primary and a secondary agent,
873 compresses the body, and formats the body using the RFC5424Layout:
874 </p>
875
876 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
877 <Configuration status="warn" name="MyApp" packages="">
878 <Appenders>
879 <Flume name="eventLogger" compress="true">
880 <Agent host="192.168.10.101" port="8800"/>
881 <Agent host="192.168.10.102" port="8800"/>
882 <RFC5424Layout enterpriseNumber="18060" includeMDC="true" appName="MyApp"/>
883 </Flume>
884 </Appenders>
885 <Loggers>
886 <Root level="error">
887 <AppenderRef ref="eventLogger"/>
888 </Root>
889 </Loggers>
890 </Configuration>]]></pre>
891 <p>
892 A sample FlumeAppender configuration that is configured with a primary and a secondary agent,
893 compresses the body, formats the body using the RFC5424Layout, and persists encrypted events to disk:
894 </p>
895
896 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
897 <Configuration status="warn" name="MyApp" packages="">
898 <Appenders>
899 <Flume name="eventLogger" compress="true" type="persistent" dataDir="./logData">
900 <Agent host="192.168.10.101" port="8800"/>
901 <Agent host="192.168.10.102" port="8800"/>
902 <RFC5424Layout enterpriseNumber="18060" includeMDC="true" appName="MyApp"/>
903 <Property name="keyProvider">MySecretProvider</Property>
904 </Flume>
905 </Appenders>
906 <Loggers>
907 <Root level="error">
908 <AppenderRef ref="eventLogger"/>
909 </Root>
910 </Loggers>
911 </Configuration>]]></pre>
912 <p>
913 A sample FlumeAppender configuration that is configured with a primary and a secondary agent,
914 compresses the body, formats the body using RFC5424Layout and passes the events to an embedded Flume
915 Agent.
916 </p>
917 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
918 <Configuration status="warn" name="MyApp" packages="">
919 <Appenders>
920 <Flume name="eventLogger" compress="true" type="Embedded">
921 <Agent host="192.168.10.101" port="8800"/>
922 <Agent host="192.168.10.102" port="8800"/>
923 <RFC5424Layout enterpriseNumber="18060" includeMDC="true" appName="MyApp"/>
924 </Flume>
925 <Console name="STDOUT">
926 <PatternLayout pattern="%d [%p] %c %m%n"/>
927 </Console>
928 </Appenders>
929 <Loggers>
930 <Logger name="EventLogger" level="info">
931 <AppenderRef ref="eventLogger"/>
932 </Logger>
933 <Root level="warn">
934 <AppenderRef ref="STDOUT"/>
935 </Root>
936 </Loggers>
937 </Configuration>]]></pre>
938 <p>
939 A sample FlumeAppender configuration that is configured with a primary and a secondary agent using
940 Flume configuration properties, compresses the body, formats the body using RFC5424Layout and passes the
941 events to an embedded Flume Agent.
942 </p>
943 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
944 <Configuration status="error" name="MyApp" packages="">
945 <Appenders>
946 <Flume name="eventLogger" compress="true" type="Embedded">
947 <Property name="channels">file</Property>
948 <Property name="channels.file.type">file</Property>
949 <Property name="channels.file.checkpointDir">target/file-channel/checkpoint</Property>
950 <Property name="channels.file.dataDirs">target/file-channel/data</Property>
951 <Property name="sinks">agent1 agent2</Property>
952 <Property name="sinks.agent1.channel">file</Property>
953 <Property name="sinks.agent1.type">avro</Property>
954 <Property name="sinks.agent1.hostname">192.168.10.101</Property>
955 <Property name="sinks.agent1.port">8800</Property>
956 <Property name="sinks.agent1.batch-size">100</Property>
957 <Property name="sinks.agent2.channel">file</Property>
958 <Property name="sinks.agent2.type">avro</Property>
959 <Property name="sinks.agent2.hostname">192.168.10.102</Property>
960 <Property name="sinks.agent2.port">8800</Property>
961 <Property name="sinks.agent2.batch-size">100</Property>
962 <Property name="sinkgroups">group1</Property>
963 <Property name="sinkgroups.group1.sinks">agent1 agent2</Property>
964 <Property name="sinkgroups.group1.processor.type">failover</Property>
965 <Property name="sinkgroups.group1.processor.priority.agent1">10</Property>
966 <Property name="sinkgroups.group1.processor.priority.agent2">5</Property>
967 <RFC5424Layout enterpriseNumber="18060" includeMDC="true" appName="MyApp"/>
968 </Flume>
969 <Console name="STDOUT">
970 <PatternLayout pattern="%d [%p] %c %m%n"/>
971 </Console>
972 </Appenders>
973 <Loggers>
974 <Logger name="EventLogger" level="info">
975 <AppenderRef ref="eventLogger"/>
976 </Logger>
977 <Root level="warn">
978 <AppenderRef ref="STDOUT"/>
979 </Root>
980 </Loggers>
981 </Configuration>]]></pre>
982 </subsection>
983 <a name="JDBCAppender"/>
984 <subsection name="JDBCAppender">
985 <p>The JDBC Appender writes log events to a relational database table using standard JDBC. It can be configured
986 to obtain JDBC connections using a JNDI <code>DataSource</code> or a custom factory method.</p>
987 <p>The JDBC Appender configured with a <code>DataSource</code> requires JNDI support so as of release 2.17.1
988 this appender will not function unless <code>log4j2.enableJndiJdbc=true</code> is configured as a system property
989 or environment variable. See the <a href="./configuration.html#enableJndiJdbc">enableJndiJdbc</a> system property.</p>
990 <p>
991 Whichever approach you take, it <strong><em>must</em></strong> be backed by a connection pool. Otherwise, logging
992 performance will suffer greatly. If batch statements are supported by the configured JDBC driver and a
993 <code>bufferSize</code> is configured to be a positive number, then log events will be batched. Note that as
994 of Log4j 2.8, there are two ways to configure log event to column mappings: the original <code>ColumnConfig</code>
995 style that only allows strings and timestamps, and the new <code>ColumnMapping</code> plugin that uses Log4j's
996 built-in type conversion to allow for more data types (this is the same plugin as in the
997 <a href="#CassandraAppender">Cassandra Appender</a>).</p>
998 <p>
999 To get off the ground quickly during development, an alternative to using a connection source based on
1000 JNDI is to use the non-pooling <code>DriverManager</code> connection source. This connection source uses
1001 a JDBC connection string, a user name, and a password. Optionally, you can also use properties.
1002 </p>
1003 <table>
1004 <caption align="top">JDBCAppender Parameters</caption>
1005 <tr>
1006 <th>Parameter Name</th>
1007 <th>Type</th>
1008 <th>Description</th>
1009 </tr>
1010 <tr>
1011 <td>name</td>
1012 <td>String</td>
1013 <td><em>Required.</em> The name of the Appender.</td>
1014 </tr>
1015 <tr>
1016 <td>ignoreExceptions</td>
1017 <td>boolean</td>
1018 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
1019 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
1020 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
1021 <a href="#FailoverAppender">FailoverAppender</a>.</td>
1022 </tr>
1023 <tr>
1024 <td>filter</td>
1025 <td>Filter</td>
1026 <td>A Filter to determine if the event should be handled by this Appender. More than one Filter may be
1027 used by using a CompositeFilter.</td>
1028 </tr>
1029 <tr>
1030 <td>bufferSize</td>
1031 <td>int</td>
1032 <td>If an integer greater than 0, this causes the appender to buffer log events and flush whenever the
1033 buffer reaches this size.</td>
1034 </tr>
1035 <tr>
1036 <td>connectionSource</td>
1037 <td>ConnectionSource</td>
1038 <td><em>Required.</em> The connections source from which database connections should be retrieved.</td>
1039 </tr>
1040 <tr>
1041 <td>tableName</td>
1042 <td>String</td>
1043 <td><em>Required.</em> The name of the database table to insert log events into.</td>
1044 </tr>
1045 <tr>
1046 <td>columnConfigs</td>
1047 <td>ColumnConfig[]</td>
1048 <td><em>Required (and/or columnMappings).</em> Information about the columns that log event data should be inserted into and how
1049 to insert that data. This is represented with multiple <code><Column></code> elements.</td>
1050 </tr>
1051 <tr>
1052 <td>columnMappings</td>
1053 <td>ColumnMapping[]</td>
1054 <td><em>Required (and/or columnConfigs).</em> A list of column mapping configurations. Each column must
1055 specify a column name. Each column can have a conversion type specified by its fully qualified class
1056 name. By default, the conversion type is <code>String</code>. If the configured type is
1057 assignment-compatible with
1058 <a class="javadoc" href="../log4j-api/apidocs/org/apache/logging/log4j/util/ReadOnlyStringMap.html">ReadOnlyStringMap</a>
1059 /
1060 <a class="javadoc" href="../log4j-api/apidocs/org/apache/logging/log4j/spi/ThreadContextMap.html">ThreadContextMap</a>
1061 or
1062 <a class="javadoc" href="../log4j-api/apidocs/org/apache/logging/log4j/spi/ThreadContextStack.html">ThreadContextStack</a>,
1063 then that column will be populated with the MDC or NDC respectively (this is database-specific how they
1064 handle inserting a <code>Map</code> or <code>List</code> value). If the configured type is
1065 assignment-compatible with <code>java.util.Date</code>, then the log timestamp will be converted to
1066 that configured date type. If the configured type is assignment-compatible with <code>java.sql.Clob</code>
1067 or <code>java.sql.NClob</code>, then the formatted event will be set as a Clob or NClob respectively
1068 (similar to the traditional ColumnConfig plugin). If a <code>literal</code> attribute is given, then its
1069 value will be used as is in the <code>INSERT</code> query without any escaping. Otherwise, the layout or
1070 pattern specified will be converted into the configured type and stored in that column.
1071 </td>
1072 </tr>
1073 <tr>
1074 <td>immediateFail</td>
1075 <td>boolean</td>
1076 <td>false</td>
1077 <td>When set to true, log events will not wait to try to reconnect and will fail immediately if the
1078 JDBC resources are not available. New in 2.11.2</td>
1079 </tr>
1080 <tr>
1081 <td>reconnectIntervalMillis</td>
1082 <td>long</td>
1083 <td>5000</td>
1084 <td>If set to a value greater than 0, after an error, the JDBCDatabaseManager will attempt to reconnect to
1085 the database after waiting the specified number of milliseconds. If the reconnect fails then
1086 an exception will be thrown (which can be caught by the application if <code>ignoreExceptions</code> is
1087 set to <code>false</code>). New in 2.11.2.</td>
1088 </tr>
1089 </table>
1090 <p>When configuring the JDBCAppender, you must specify a <code>ConnectionSource</code> implementation from
1091 which the Appender gets JDBC connections. You must use exactly one of the following nested elements:</p>
1092 <ul>
1093 <li><a href="#JDBCDataSource"><code><DataSource></code></a>: Uses JNDI.</li>
1094 <li><a href="#JDBCConnectionFactory"><code><ConnectionFactory></code></a>: Points to a class-method pair to provide JDBC connections.</li>
1095 <li><a href="#JDBCDriverManager"><code><DriverManager></code></a>: A quick and dirty way to get off the ground, no connection pooling.</li>
1096 <li><a href="#JDBCPoolingDriver"><code><PoolingDriver></code></a>: Uses Apache Commons DBCP to provide connection pooling.</li>
1097 </ul>
1098 <a name="JDBCDataSource"/>
1099 <table>
1100 <caption align="top">DataSource Parameters</caption>
1101 <tr>
1102 <th>Parameter Name</th>
1103 <th>Type</th>
1104 <th>Description</th>
1105 </tr>
1106 <tr>
1107 <td>jndiName</td>
1108 <td>String</td>
1109 <td><em>Required.</em> The full, prefixed JNDI name that the <code>javax.sql.DataSource</code> is bound
1110 to, such as <code>java:/comp/env/jdbc/LoggingDatabase</code>. The <code>DataSource</code> must be backed
1111 by a connection pool; otherwise, logging will be very slow.</td>
1112 </tr>
1113 </table>
1114 <a name="JDBCConnectionFactory"/>
1115 <table>
1116 <caption align="top">ConnectionFactory Parameters</caption>
1117 <tr>
1118 <th>Parameter Name</th>
1119 <th>Type</th>
1120 <th>Description</th>
1121 </tr>
1122 <tr>
1123 <td>class</td>
1124 <td>Class</td>
1125 <td><em>Required.</em> The fully qualified name of a class containing a static factory method for
1126 obtaining JDBC connections.</td>
1127 </tr>
1128 <tr>
1129 <td>method</td>
1130 <td>Method</td>
1131 <td><em>Required.</em> The name of a static factory method for obtaining JDBC connections. This method
1132 must have no parameters and its return type must be either <code>java.sql.Connection</code> or
1133 <code>DataSource</code>. If the method returns <code>Connection</code>s, it must obtain them from a
1134 connection pool (and they will be returned to the pool when Log4j is done with them); otherwise, logging
1135 will be very slow. If the method returns a <code>DataSource</code>, the <code>DataSource</code> will
1136 only be retrieved once, and it must be backed by a connection pool for the same reasons.</td>
1137 </tr>
1138 </table>
1139 <a name="JDBCDriverManager"/>
1140 <table>
1141 <caption align="top">DriverManager Parameters</caption>
1142 <tr>
1143 <th>Parameter Name</th>
1144 <th>Type</th>
1145 <th>Description</th>
1146 </tr>
1147 <tr>
1148 <td>connectionString</td>
1149 <td>String</td>
1150 <td><em>Required.</em> The driver-specific JDBC connection string.</td>
1151 </tr>
1152 <tr>
1153 <td>userName</td>
1154 <td>String</td>
1155 <td>The database user name. You cannot specify both properties and a user name or password.</td>
1156 </tr>
1157 <tr>
1158 <td>password</td>
1159 <td>String</td>
1160 <td>The database password. You cannot specify both properties and a user name or password.</td>
1161 </tr>
1162 <tr>
1163 <td>driverClassName</td>
1164 <td>String</td>
1165 <td>The JDBC driver class name. Some old JDBC Driver can only be discovered by explicitly loading them by class name.</td>
1166 </tr>
1167 <tr>
1168 <td>properties</td>
1169 <td>Property[]</td>
1170 <td>A list of properties. You cannot specify both properties and a user name or password.</td>
1171 </tr>
1172 </table>
1173 <a name="JDBCPoolingDriver"/>
1174 <table>
1175 <caption align="top">PoolingDriver Parameters (Apache Commons DBCP)</caption>
1176 <tr>
1177 <th>Parameter Name</th>
1178 <th>Type</th>
1179 <th>Description</th>
1180 </tr>
1181 <tr>
1182 <td>DriverManager parameters</td>
1183 <td>DriverManager parameters</td>
1184 <td>This connection source inherits all parameter from the DriverManager connection source.</td>
1185 </tr>
1186 <tr>
1187 <td>poolName</td>
1188 <td>String</td>
1189 <td>The pool name used to pool JDBC Connections. Defaults to <code>example</code>. You can use the JDBC
1190 connection string prefix <code>jdbc:apache:commons:dbcp:</code> followed by the pool name if you want
1191 to use a pooled connection elsewhere. For example: <code>jdbc:apache:commons:dbcp:example</code>.</td>
1192 </tr>
1193 <tr>
1194 <td>PoolableConnectionFactory</td>
1195 <td>PoolableConnectionFactory element</td>
1196 <td>Defines a PoolableConnectionFactory.</td>
1197 </tr>
1198 </table>
1199 <a name="JDBCPoolableConnectionFactory"/>
1200 <table>
1201 <caption align="top">PoolableConnectionFactory Parameters (Apache Commons DBCP)</caption>
1202 <tr>
1203 <th>Parameter Name</th>
1204 <th>Type</th>
1205 <th>Description</th>
1206 </tr>
1207 <tr>
1208 <td>autoCommitOnReturn</td>
1209 <td>boolean</td>
1210 <td>See <a href="http://commons.apache.org/proper/commons-dbcp/api-2.4.0/org/apache/commons/dbcp2/PoolableConnectionFactory.html">Apache Commons DBCP PoolableConnectionFactory.</a></td>
1211 </tr>
1212 <tr>
1213 <td>cacheState</td>
1214 <td>boolean</td>
1215 <td>See <a href="http://commons.apache.org/proper/commons-dbcp/api-2.4.0/org/apache/commons/dbcp2/PoolableConnectionFactory.html">Apache Commons DBCP PoolableConnectionFactory.</a></td>
1216 </tr>
1217 <tr>
1218 <td>ConnectionInitSqls</td>
1219 <td>Strings</td>
1220 <td>See <a href="http://commons.apache.org/proper/commons-dbcp/api-2.4.0/org/apache/commons/dbcp2/PoolableConnectionFactory.html">Apache Commons DBCP PoolableConnectionFactory.</a></td>
1221 </tr>
1222 <tr>
1223 <td>defaultAutoCommit</td>
1224 <td>boolean</td>
1225 <td>See <a href="http://commons.apache.org/proper/commons-dbcp/api-2.4.0/org/apache/commons/dbcp2/PoolableConnectionFactory.html">Apache Commons DBCP PoolableConnectionFactory.</a></td>
1226 </tr>
1227 <tr>
1228 <td>defaultCatalog</td>
1229 <td>String</td>
1230 <td>See <a href="http://commons.apache.org/proper/commons-dbcp/api-2.4.0/org/apache/commons/dbcp2/PoolableConnectionFactory.html">Apache Commons DBCP PoolableConnectionFactory.</a></td>
1231 </tr>
1232 <tr>
1233 <td>defaultQueryTimeoutSeconds</td>
1234 <td>integer</td>
1235 <td>See <a href="http://commons.apache.org/proper/commons-dbcp/api-2.4.0/org/apache/commons/dbcp2/PoolableConnectionFactory.html">Apache Commons DBCP PoolableConnectionFactory.</a></td>
1236 </tr>
1237 <tr>
1238 <td>defaultReadOnly</td>
1239 <td>boolean</td>
1240 <td>See <a href="http://commons.apache.org/proper/commons-dbcp/api-2.4.0/org/apache/commons/dbcp2/PoolableConnectionFactory.html">Apache Commons DBCP PoolableConnectionFactory.</a></td>
1241 </tr>
1242 <tr>
1243 <td>defaultTransactionIsolation</td>
1244 <td>integer</td>
1245 <td>See <a href="http://commons.apache.org/proper/commons-dbcp/api-2.4.0/org/apache/commons/dbcp2/PoolableConnectionFactory.html">Apache Commons DBCP PoolableConnectionFactory.</a></td>
1246 </tr>
1247 <tr>
1248 <td>disconnectionSqlCodes</td>
1249 <td>Strings</td>
1250 <td>See <a href="http://commons.apache.org/proper/commons-dbcp/api-2.4.0/org/apache/commons/dbcp2/PoolableConnectionFactory.html">Apache Commons DBCP PoolableConnectionFactory.</a></td>
1251 </tr>
1252 <tr>
1253 <td>fastFailValidation</td>
1254 <td>boolean</td>
1255 <td>See <a href="http://commons.apache.org/proper/commons-dbcp/api-2.4.0/org/apache/commons/dbcp2/PoolableConnectionFactory.html">Apache Commons DBCP PoolableConnectionFactory.</a></td>
1256 </tr>
1257 <tr>
1258 <td>maxConnLifetimeMillis</td>
1259 <td>long</td>
1260 <td>See <a href="http://commons.apache.org/proper/commons-dbcp/api-2.4.0/org/apache/commons/dbcp2/PoolableConnectionFactory.html">Apache Commons DBCP PoolableConnectionFactory.</a></td>
1261 </tr>
1262 <tr>
1263 <td>maxOpenPreparedStatements</td>
1264 <td>integer</td>
1265 <td>See <a href="http://commons.apache.org/proper/commons-dbcp/api-2.4.0/org/apache/commons/dbcp2/PoolableConnectionFactory.html">Apache Commons DBCP PoolableConnectionFactory.</a></td>
1266 </tr>
1267 <tr>
1268 <td>poolStatements</td>
1269 <td>boolean</td>
1270 <td>See <a href="http://commons.apache.org/proper/commons-dbcp/api-2.4.0/org/apache/commons/dbcp2/PoolableConnectionFactory.html">Apache Commons DBCP PoolableConnectionFactory.</a></td>
1271 </tr>
1272 <tr>
1273 <td>rollbackOnReturn</td>
1274 <td>boolean</td>
1275 <td>See <a href="http://commons.apache.org/proper/commons-dbcp/api-2.4.0/org/apache/commons/dbcp2/PoolableConnectionFactory.html">Apache Commons DBCP PoolableConnectionFactory.</a></td>
1276 </tr>
1277 <tr>
1278 <td>validationQuery</td>
1279 <td>String</td>
1280 <td>See <a href="http://commons.apache.org/proper/commons-dbcp/api-2.4.0/org/apache/commons/dbcp2/PoolableConnectionFactory.html">Apache Commons DBCP PoolableConnectionFactory.</a></td>
1281 </tr>
1282 <tr>
1283 <td>validationQueryTimeoutSeconds</td>
1284 <td>integer</td>
1285 <td>See <a href="http://commons.apache.org/proper/commons-dbcp/api-2.4.0/org/apache/commons/dbcp2/PoolableConnectionFactory.html">Apache Commons DBCP PoolableConnectionFactory.</a></td>
1286 </tr>
1287 </table>
1288 <p>When configuring the JDBCAppender, use the nested <code><Column></code> elements to specify which
1289 columns in the table should be written to and how to write to them. The JDBCAppender uses this information
1290 to formulate a <code>PreparedStatement</code> to insert records without SQL injection vulnerability.</p>
1291 <table>
1292 <caption align="top">Column Parameters</caption>
1293 <tr>
1294 <th>Parameter Name</th>
1295 <th>Type</th>
1296 <th>Description</th>
1297 </tr>
1298 <tr>
1299 <td>name</td>
1300 <td>String</td>
1301 <td><em>Required.</em> The name of the database column.</td>
1302 </tr>
1303 <tr>
1304 <td>pattern</td>
1305 <td>String</td>
1306 <td>Use this attribute to insert a value or values from the log event in this column using a
1307 <code>PatternLayout</code> pattern. Simply specify any legal pattern in this attribute. Either this
1308 attribute, <code>literal</code>, or <code>isEventTimestamp="true"</code> must be specified, but not more
1309 than one of these.</td>
1310 </tr>
1311 <tr>
1312 <td>literal</td>
1313 <td>String</td>
1314 <td>
1315 <p>Use this attribute to insert a literal value in this column. The value will be included directly in
1316 the insert SQL, without any quoting (which means that if you want this to be a string, your value should
1317 contain single quotes around it like this: <code>literal="'Literal String'"</code>). This is especially
1318 useful for databases that don't support identity columns. For example, if you are using Oracle you could
1319 specify <code>literal="NAME_OF_YOUR_SEQUENCE.NEXTVAL"</code> to insert a unique ID in an ID column.
1320 Either this attribute, <code>pattern</code>, or <code>isEventTimestamp="true"</code> must be specified,
1321 but not more than one of these.
1322 </p>
1323 </td>
1324 </tr>
1325 <tr>
1326 <td>parameter</td>
1327 <td>String</td>
1328 <td>
1329 <p>Use this attribute to insert an expression with a parameter marker '?' in this column. The value will be included directly in
1330 the insert SQL, without any quoting (which means that if you want this to be a string, your value should
1331 contain single quotes around it like this:
1332 </p>
1333 <p>
1334 <code><ColumnMapping name="instant" parameter="TIMESTAMPADD('MILLISECOND', ?, TIMESTAMP '1970-01-01')"/></code>
1335 </p>
1336 <p>
1337 You can only specify one of <code>literal</code> or <code>parameter</code>.
1338 </p>
1339 </td>
1340 </tr>
1341 <tr>
1342 <td>isEventTimestamp</td>
1343 <td>boolean</td>
1344 <td>Use this attribute to insert the event timestamp in this column, which should be a SQL datetime. The
1345 value will be inserted as a <code>java.sql.Types.TIMESTAMP</code>. Either this attribute (equal to
1346 <code>true</code>), <code>pattern</code>, or <code>isEventTimestamp</code> must be specified, but not
1347 more than one of these.</td>
1348 </tr>
1349 <tr>
1350 <td>isUnicode</td>
1351 <td>boolean</td>
1352 <td>This attribute is ignored unless <code>pattern</code> is specified. If <code>true</code> or omitted
1353 (default), the value will be inserted as unicode (<code>setNString</code> or <code>setNClob</code>).
1354 Otherwise, the value will be inserted non-unicode (<code>setString</code> or <code>setClob</code>).</td>
1355 </tr>
1356 <tr>
1357 <td>isClob</td>
1358 <td>boolean</td>
1359 <td>This attribute is ignored unless <code>pattern</code> is specified. Use this attribute to indicate
1360 that the column stores Character Large Objects (CLOBs). If <code>true</code>, the value will be inserted
1361 as a CLOB (<code>setClob</code> or <code>setNClob</code>). If <code>false</code> or omitted (default),
1362 the value will be inserted as a VARCHAR or NVARCHAR (<code>setString</code> or <code>setNString</code>).
1363 </td>
1364 </tr>
1365 </table>
1366 <table>
1367 <caption align="top">ColumnMapping Parameters</caption>
1368 <tr>
1369 <th>Parameter Name</th>
1370 <th>Type</th>
1371 <th>Description</th>
1372 </tr>
1373 <tr>
1374 <td>name</td>
1375 <td>String</td>
1376 <td><em>Required.</em> The name of the database column.</td>
1377 </tr>
1378 <tr>
1379 <td>pattern</td>
1380 <td>String</td>
1381 <td>Use this attribute to insert a value or values from the log event in this column using a
1382 <code>PatternLayout</code> pattern. Simply specify any legal pattern in this attribute. Either this
1383 attribute, <code>literal</code>, or <code>isEventTimestamp="true"</code> must be specified, but not more
1384 than one of these.</td>
1385 </tr>
1386 <tr>
1387 <td>literal</td>
1388 <td>String</td>
1389 <td>Use this attribute to insert a literal value in this column. The value will be included directly in
1390 the insert SQL, without any quoting (which means that if you want this to be a string, your value should
1391 contain single quotes around it like this: <code>literal="'Literal String'"</code>). This is especially
1392 useful for databases that don't support identity columns. For example, if you are using Oracle you could
1393 specify <code>literal="NAME_OF_YOUR_SEQUENCE.NEXTVAL"</code> to insert a unique ID in an ID column.
1394 Either this attribute, <code>pattern</code>, or <code>isEventTimestamp="true"</code> must be specified,
1395 but not more than one of these.</td>
1396 </tr>
1397 <tr>
1398 <td>layout</td>
1399 <td>Layout</td>
1400 <td>The Layout to format the LogEvent.</td>
1401 </tr>
1402 <tr>
1403 <td>type</td>
1404 <td>String</td>
1405 <td>Conversion type name, a fully-qualified class name.</td>
1406 </tr>
1407 </table>
1408 <p>
1409 Here are a couple sample configurations for the JDBCAppender, as well as a sample factory implementation
1410 that uses Commons Pooling and Commons DBCP to pool database connections:
1411 </p>
1412
1413 <pre class="prettyprint linenums lang-xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
1414 <Configuration status="error">
1415 <Appenders>
1416 <JDBC name="databaseAppender" tableName="dbo.application_log">
1417 <DataSource jndiName="java:/comp/env/jdbc/LoggingDataSource" />
1418 <Column name="eventDate" isEventTimestamp="true" />
1419 <Column name="level" pattern="%level" />
1420 <Column name="logger" pattern="%logger" />
1421 <Column name="message" pattern="%message" />
1422 <Column name="exception" pattern="%ex{full}" />
1423 </JDBC>
1424 </Appenders>
1425 <Loggers>
1426 <Root level="warn">
1427 <AppenderRef ref="databaseAppender"/>
1428 </Root>
1429 </Loggers>
1430 </Configuration>]]></pre>
1431
1432 <pre class="prettyprint linenums lang-xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
1433 <Configuration status="error">
1434 <Appenders>
1435 <JDBC name="databaseAppender" tableName="LOGGING.APPLICATION_LOG">
1436 <ConnectionFactory class="net.example.db.ConnectionFactory" method="getDatabaseConnection" />
1437 <Column name="EVENT_ID" literal="LOGGING.APPLICATION_LOG_SEQUENCE.NEXTVAL" />
1438 <Column name="EVENT_DATE" isEventTimestamp="true" />
1439 <Column name="LEVEL" pattern="%level" />
1440 <Column name="LOGGER" pattern="%logger" />
1441 <Column name="MESSAGE" pattern="%message" />
1442 <Column name="THROWABLE" pattern="%ex{full}" />
1443 </JDBC>
1444 </Appenders>
1445 <Loggers>
1446 <Root level="warn">
1447 <AppenderRef ref="databaseAppender"/>
1448 </Root>
1449 </Loggers>
1450 </Configuration>]]></pre>
1451 <pre class="prettyprint linenums lang-java"><![CDATA[package net.example.db;
1452
1453 import java.sql.Connection;
1454 import java.sql.SQLException;
1455 import java.util.Properties;
1456
1457 import javax.sql.DataSource;
1458
1459 import org.apache.commons.dbcp.DriverManagerConnectionFactory;
1460 import org.apache.commons.dbcp.PoolableConnection;
1461 import org.apache.commons.dbcp.PoolableConnectionFactory;
1462 import org.apache.commons.dbcp.PoolingDataSource;
1463 import org.apache.commons.pool.impl.GenericObjectPool;
1464
1465 public class ConnectionFactory {
1466 private static interface Singleton {
1467 final ConnectionFactory INSTANCE = new ConnectionFactory();
1468 }
1469
1470 private final DataSource dataSource;
1471
1472 private ConnectionFactory() {
1473 Properties properties = new Properties();
1474 properties.setProperty("user", "logging");
1475 properties.setProperty("password", "abc123"); // or get properties from some configuration file
1476
1477 GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>();
1478 DriverManagerConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
1479 "jdbc:mysql://example.org:3306/exampleDb", properties
1480 );
1481 new PoolableConnectionFactory(
1482 connectionFactory, pool, null, "SELECT 1", 3, false, false, Connection.TRANSACTION_READ_COMMITTED
1483 );
1484
1485 this.dataSource = new PoolingDataSource(pool);
1486 }
1487
1488 public static Connection getDatabaseConnection() throws SQLException {
1489 return Singleton.INSTANCE.dataSource.getConnection();
1490 }
1491 }]]></pre>
1492 <p>
1493 This appender is <a href="messages.html#MapMessage">MapMessage</a>-aware.
1494 </p>
1495 <p>
1496 The following configuration uses a <code>MessageLayout</code> to indicate that the Appender should match
1497 the keys of a <code>MapMessage</code> to the names of <code>ColumnMapping</code>s when setting the
1498 values of the Appender's SQL INSERT statement. This let you insert rows for custom values in a
1499 database table based on a Log4j <code>MapMessage</code> instead of values from <code>LogEvent</code>s.
1500 </p>
1501 <pre class="prettyprint linenums lang-xml"><![CDATA[<Configuration status="debug">
1502
1503 <Appenders>
1504 <Console name="STDOUT">
1505 <PatternLayout pattern="%C{1.} %m %level MDC%X%n"/>
1506 </Console>
1507 <Jdbc name="databaseAppender" tableName="dsLogEntry" ignoreExceptions="false">
1508 <DataSource jndiName="java:/comp/env/jdbc/TestDataSourceAppender" />
1509 <ColumnMapping name="Id" />
1510 <ColumnMapping name="ColumnA" />
1511 <ColumnMapping name="ColumnB" />
1512 <MessageLayout />
1513 </Jdbc>
1514 </Appenders>
1515
1516 <Loggers>
1517 <Logger name="org.apache.logging.log4j.core.appender.db" level="debug" additivity="false">
1518 <AppenderRef ref="databaseAppender" />
1519 </Logger>
1520
1521 <Root level="fatal">
1522 <AppenderRef ref="STDOUT"/>
1523 </Root>
1524 </Loggers>
1525
1526 </Configuration>]]></pre>
1527 </subsection>
1528 <a name="JMSAppender"/>
1529 <!-- cool URLs don't change, so here are some old anchors -->
1530 <a name="JMSQueueAppender"/>
1531 <a name="JMSTopicAppender"/>
1532 <subsection name="JMS Appender">
1533 <p>The JMS Appender sends the formatted log event to a JMS Destination.</p>
1534 <p>The JMS Appender requires JNDI support so as of release 2.12.3 this appender will not function unless
1535 <code>log4j2.enableJndiJms=true</code> is configured as a system property or environment
1536 variable. See the <a href="./configuration.html#enableJndiJms">enableJndiJms</a> system property.</p>
1537 <p>
1538 Note that in Log4j 2.0, this appender was split into a JMSQueueAppender and a JMSTopicAppender. Starting
1539 in Log4j 2.1, these appenders were combined into the JMS Appender which makes no distinction between queues
1540 and topics. However, configurations written for 2.0 which use the <code><JMSQueue/></code> or
1541 <code><JMSTopic/></code> elements will continue to work with the new <code><JMS/></code>
1542 configuration element.
1543 </p>
1544 <table>
1545 <caption align="top">JMS Appender Parameters</caption>
1546 <tr>
1547 <th>Parameter Name</th>
1548 <th>Type</th>
1549 <th>Default</th>
1550 <th>Description</th>
1551 </tr>
1552 <tr>
1553 <td>factoryBindingName</td>
1554 <td>String</td>
1555 <td><em>Required</em></td>
1556 <td>The name to locate in the Context that provides the
1557 <a class="javadoc" href="http://download.oracle.com/javaee/5/api/javax/jms/ConnectionFactory.html">ConnectionFactory</a>.
1558 This can be any subinterface of <code>ConnectionFactory</code> as well.
1559 </td>
1560 </tr>
1561 <tr>
1562 <td>factoryName</td>
1563 <td>String</td>
1564 <td><em>Required</em></td>
1565 <td>The fully qualified class name that should be used to define the Initial Context Factory as defined in
1566 <a class="javadoc" href="http://download.oracle.com/javase/7/docs/api/javax/naming/Context.html#INITIAL_CONTEXT_FACTORY">INITIAL_CONTEXT_FACTORY</a>.
1567 If a factoryName is specified without a providerURL a warning message will be logged as this is
1568 likely to cause problems.
1569 </td>
1570 </tr>
1571 <tr>
1572 <td>filter</td>
1573 <td>Filter</td>
1574 <td>null</td>
1575 <td>A Filter to determine if the event should be handled by this Appender. More than one Filter
1576 may be used by using a CompositeFilter.</td>
1577 </tr>
1578 <tr>
1579 <td>layout</td>
1580 <td>Layout</td>
1581 <td><em>Required</em></td>
1582 <td>
1583 The Layout to use to format the LogEvent.
1584 <em>New since 2.9, in previous versions SerializedLayout was default.</em>
1585 </td>
1586 </tr>
1587 <tr>
1588 <td>name</td>
1589 <td>String</td>
1590 <td><em>Required</em></td>
1591 <td>The name of the Appender. </td>
1592 </tr>
1593 <tr>
1594 <td>password</td>
1595 <td>String</td>
1596 <td>null</td>
1597 <td>The password to use to create the JMS connection.</td>
1598 </tr>
1599 <tr>
1600 <td>providerURL</td>
1601 <td>String</td>
1602 <td><em>Required</em></td>
1603 <td>The URL of the provider to use as defined by
1604 <a class="javadoc" href="http://download.oracle.com/javase/7/docs/api/javax/naming/Context.html#PROVIDER_URL">PROVIDER_URL</a>.
1605 </td>
1606 </tr>
1607 <tr>
1608 <td>destinationBindingName</td>
1609 <td>String</td>
1610 <td><em>Required</em></td>
1611 <td>
1612 The name to use to locate the
1613 <a class="javadoc" href="http://download.oracle.com/javaee/5/api/javax/jms/Destination.html">Destination</a>.
1614 This can be a <code>Queue</code> or <code>Topic</code>, and as such, the attribute names
1615 <code>queueBindingName</code> and <code>topicBindingName</code> are aliases to maintain compatibility
1616 with the Log4j 2.0 JMS appenders.
1617 </td>
1618 </tr>
1619 <tr>
1620 <td>securityPrincipalName</td>
1621 <td>String</td>
1622 <td>null</td>
1623 <td>The name of the identity of the Principal as specified by
1624 <a class="javadoc" href="http://download.oracle.com/javase/7/docs/api/javax/naming/Context.html#SECURITY_PRINCIPAL">SECURITY_PRINCIPAL</a>.
1625 If a securityPrincipalName is specified without securityCredentials a warning message will be
1626 logged as this is likely to cause problems.</td>
1627 </tr>
1628 <tr>
1629 <td>securityCredentials</td>
1630 <td>String</td>
1631 <td>null</td>
1632 <td>The security credentials for the principal as specified by
1633 <a class="javadoc" href="http://download.oracle.com/javase/7/docs/api/javax/naming/Context.html#SECURITY_CREDENTIALS">SECURITY_CREDENTIALS</a>.
1634 </td>
1635 </tr>
1636 <tr>
1637 <td>ignoreExceptions</td>
1638 <td>boolean</td>
1639 <td>true</td>
1640 <td>When <code>true</code>, exceptions caught while appending events are
1641 internally logged and then ignored. When <code>false</code> exceptions are propagated to the
1642 caller. You must set this to <code>false</code> when wrapping this Appender in a
1643 <a href="#FailoverAppender">FailoverAppender</a>.</td>
1644 </tr>
1645 <tr>
1646 <td>immediateFail</td>
1647 <td>boolean</td>
1648 <td>false</td>
1649 <td>When set to true, log events will not wait to try to reconnect and will fail immediately if the
1650 JMS resources are not available. New in 2.9.</td>
1651 </tr>
1652 <tr>
1653 <td>reconnectIntervalMillis</td>
1654 <td>long</td>
1655 <td>5000</td>
1656 <td>If set to a value greater than 0, after an error, the JMSManager will attempt to reconnect to
1657 the broker after waiting the specified number of milliseconds. If the reconnect fails then
1658 an exception will be thrown (which can be caught by the application if <code>ignoreExceptions</code> is
1659 set to <code>false</code>). New in 2.9.</td>
1660 </tr>
1661 <tr>
1662 <td>urlPkgPrefixes</td>
1663 <td>String</td>
1664 <td>null</td>
1665 <td>A colon-separated list of package prefixes for the class name of the factory class that will create
1666 a URL context factory as defined by
1667 <a class="javadoc" href="http://download.oracle.com/javase/7/docs/api/javax/naming/Context.html#URL_PKG_PREFIXES">URL_PKG_PREFIXES</a>.
1668 </td>
1669 </tr>
1670 <tr>
1671 <td>userName</td>
1672 <td>String</td>
1673 <td>null</td>
1674 <td>The user id used to create the JMS connection.</td>
1675 </tr>
1676 </table>
1677 <p>
1678 Here is a sample JMS Appender configuration:
1679 </p>
1680
1681 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
1682 <Configuration status="warn" name="MyApp">
1683 <Appenders>
1684 <JMS name="jmsQueue" destinationBindingName="MyQueue"
1685 factoryBindingName="MyQueueConnectionFactory">
1686 <JsonLayout properties="true"/>
1687 </JMS>
1688 </Appenders>
1689 <Loggers>
1690 <Root level="error">
1691 <AppenderRef ref="jmsQueue"/>
1692 </Root>
1693 </Loggers>
1694 </Configuration>]]></pre>
1695
1696 <p>
1697 To map your Log4j <code>MapMessage</code>s to JMS <code>javax.jms.MapMessage</code>s, set the
1698 layout of the appender to <code>MessageLayout</code> with <code><MessageLayout /></code> (Since 2.9.):
1699 </p>
1700
1701 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
1702 <Configuration status="warn" name="MyApp">
1703 <Appenders>
1704 <JMS name="jmsQueue" destinationBindingName="MyQueue"
1705 factoryBindingName="MyQueueConnectionFactory">
1706 <MessageLayout />
1707 </JMS>
1708 </Appenders>
1709 <Loggers>
1710 <Root level="error">
1711 <AppenderRef ref="jmsQueue"/>
1712 </Root>
1713 </Loggers>
1714 </Configuration>]]></pre>
1715
1716 </subsection>
1717 <a name="JPAAppender"/>
1718 <subsection name="JPAAppender">
1719 <p>
1720 As of Log4j 2.11.0, JPA support has moved from the existing module <code>logj-core</code> to the new module <code>log4j-jpa</code>.
1721 </p>
1722 <p>The JPAAppender writes log events to a relational database table using the Java Persistence API 2.1.
1723 It requires the API and a provider implementation be on the classpath. It also requires a decorated entity
1724 configured to persist to the table desired. The entity should either extend
1725 <code>org.apache.logging.log4j.core.appender.db.jpa.BasicLogEventEntity</code> (if you mostly want to
1726 use the default mappings) and provide at least an <code>@Id</code> property, or
1727 <code>org.apache.logging.log4j.core.appender.db.jpa.AbstractLogEventWrapperEntity</code> (if you want
1728 to significantly customize the mappings). See the Javadoc for these two classes for more information. You
1729 can also consult the source code of these two classes as an example of how to implement the entity.</p>
1730 <table>
1731 <caption align="top">JPAAppender Parameters</caption>
1732 <tr>
1733 <th>Parameter Name</th>
1734 <th>Type</th>
1735 <th>Description</th>
1736 </tr>
1737 <tr>
1738 <td>name</td>
1739 <td>String</td>
1740 <td><em>Required.</em> The name of the Appender.</td>
1741 </tr>
1742 <tr>
1743 <td>ignoreExceptions</td>
1744 <td>boolean</td>
1745 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
1746 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
1747 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
1748 <a href="#FailoverAppender">FailoverAppender</a>.</td>
1749 </tr>
1750 <tr>
1751 <td>filter</td>
1752 <td>Filter</td>
1753 <td>A Filter to determine if the event should be handled by this Appender. More than one Filter may be
1754 used by using a CompositeFilter.</td>
1755 </tr>
1756 <tr>
1757 <td>bufferSize</td>
1758 <td>int</td>
1759 <td>If an integer greater than 0, this causes the appender to buffer log events and flush whenever the
1760 buffer reaches this size.</td>
1761 </tr>
1762 <tr>
1763 <td>entityClassName</td>
1764 <td>String</td>
1765 <td><em>Required.</em> The fully qualified name of the concrete LogEventWrapperEntity implementation that
1766 has JPA annotations mapping it to a database table.</td>
1767 </tr>
1768 <tr>
1769 <td>persistenceUnitName</td>
1770 <td>String</td>
1771 <td><em>Required.</em> The name of the JPA persistence unit that should be used for persisting log
1772 events.</td>
1773 </tr>
1774 </table>
1775 <p>
1776 Here is a sample configuration for the JPAAppender. The first XML sample is the Log4j configuration file,
1777 the second is the <code>persistence.xml</code> file. EclipseLink is assumed here, but any JPA 2.1 or higher
1778 provider will do. You should <em>always</em> create a <em>separate</em> persistence unit for logging, for
1779 two reasons. First, <code><shared-cache-mode></code> <em>must</em> be set to "NONE," which is usually
1780 not desired in normal JPA usage. Also, for performance reasons the logging entity should be isolated in its
1781 own persistence unit away from all other entities and you should use a non-JTA data source. Note that your
1782 persistence unit <em>must</em> also contain <code><class></code> elements for all of the
1783 <code>org.apache.logging.log4j.core.appender.db.jpa.converter</code> converter classes.
1784 </p>
1785
1786 <pre class="prettyprint linenums lang-xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
1787 <Configuration status="error">
1788 <Appenders>
1789 <JPA name="databaseAppender" persistenceUnitName="loggingPersistenceUnit"
1790 entityClassName="com.example.logging.JpaLogEntity" />
1791 </Appenders>
1792 <Loggers>
1793 <Root level="warn">
1794 <AppenderRef ref="databaseAppender"/>
1795 </Root>
1796 </Loggers>
1797 </Configuration>]]></pre>
1798
1799 <pre class="prettyprint linenums lang-xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
1800 <persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
1801 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1802 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
1803 http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
1804 version="2.1">
1805
1806 <persistence-unit name="loggingPersistenceUnit" transaction-type="RESOURCE_LOCAL">
1807 <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
1808 <class>org.apache.logging.log4j.core.appender.db.jpa.converter.ContextMapAttributeConverter</class>
1809 <class>org.apache.logging.log4j.core.appender.db.jpa.converter.ContextMapJsonAttributeConverter</class>
1810 <class>org.apache.logging.log4j.core.appender.db.jpa.converter.ContextStackAttributeConverter</class>
1811 <class>org.apache.logging.log4j.core.appender.db.jpa.converter.ContextStackJsonAttributeConverter</class>
1812 <class>org.apache.logging.log4j.core.appender.db.jpa.converter.MarkerAttributeConverter</class>
1813 <class>org.apache.logging.log4j.core.appender.db.jpa.converter.MessageAttributeConverter</class>
1814 <class>org.apache.logging.log4j.core.appender.db.jpa.converter.StackTraceElementAttributeConverter</class>
1815 <class>org.apache.logging.log4j.core.appender.db.jpa.converter.ThrowableAttributeConverter</class>
1816 <class>com.example.logging.JpaLogEntity</class>
1817 <non-jta-data-source>jdbc/LoggingDataSource</non-jta-data-source>
1818 <shared-cache-mode>NONE</shared-cache-mode>
1819 </persistence-unit>
1820
1821 </persistence>]]></pre>
1822
1823 <pre class="prettyprint linenums lang-java"><![CDATA[package com.example.logging;
1824 ...
1825 @Entity
1826 @Table(name="application_log", schema="dbo")
1827 public class JpaLogEntity extends BasicLogEventEntity {
1828 private static final long serialVersionUID = 1L;
1829 private long id = 0L;
1830
1831 public TestEntity() {
1832 super(null);
1833 }
1834 public TestEntity(LogEvent wrappedEvent) {
1835 super(wrappedEvent);
1836 }
1837
1838 @Id
1839 @GeneratedValue(strategy = GenerationType.IDENTITY)
1840 @Column(name = "id")
1841 public long getId() {
1842 return this.id;
1843 }
1844
1845 public void setId(long id) {
1846 this.id = id;
1847 }
1848
1849 // If you want to override the mapping of any properties mapped in BasicLogEventEntity,
1850 // just override the getters and re-specify the annotations.
1851 }]]></pre>
1852
1853 <pre class="prettyprint linenums lang-java"><![CDATA[package com.example.logging;
1854 ...
1855 @Entity
1856 @Table(name="application_log", schema="dbo")
1857 public class JpaLogEntity extends AbstractLogEventWrapperEntity {
1858 private static final long serialVersionUID = 1L;
1859 private long id = 0L;
1860
1861 public TestEntity() {
1862 super(null);
1863 }
1864 public TestEntity(LogEvent wrappedEvent) {
1865 super(wrappedEvent);
1866 }
1867
1868 @Id
1869 @GeneratedValue(strategy = GenerationType.IDENTITY)
1870 @Column(name = "logEventId")
1871 public long getId() {
1872 return this.id;
1873 }
1874
1875 public void setId(long id) {
1876 this.id = id;
1877 }
1878
1879 @Override
1880 @Enumerated(EnumType.STRING)
1881 @Column(name = "level")
1882 public Level getLevel() {
1883 return this.getWrappedEvent().getLevel();
1884 }
1885
1886 @Override
1887 @Column(name = "logger")
1888 public String getLoggerName() {
1889 return this.getWrappedEvent().getLoggerName();
1890 }
1891
1892 @Override
1893 @Column(name = "message")
1894 @Convert(converter = MyMessageConverter.class)
1895 public Message getMessage() {
1896 return this.getWrappedEvent().getMessage();
1897 }
1898 ...
1899 }]]></pre>
1900 </subsection>
1901 <a name="HttpAppender"/>
1902 <subsection name="HttpAppender">
1903 <p>
1904 The HttpAppender sends log events over HTTP. A Layout must be provided to format the LogEvent.
1905 </p>
1906 <p>
1907 Will set the <code>Content-Type</code> header according to the layout. Additional headers can be specified
1908 with embedded Property elements.
1909 </p>
1910 <p>
1911 Will wait for response from server, and throw error if no 2xx response is received.
1912 </p>
1913 <p>
1914 Implemented with
1915 <a href="https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html">HttpURLConnection</a>.
1916 </p>
1917 <table>
1918 <caption align="top">HttpAppender Parameters</caption>
1919 <tr>
1920 <th>Parameter Name</th>
1921 <th>Type</th>
1922 <th>Description</th>
1923 </tr>
1924 <tr>
1925 <td>name</td>
1926 <td>String</td>
1927 <td>The name of the Appender.</td>
1928 </tr>
1929 <tr>
1930 <td>filter</td>
1931 <td>Filter</td>
1932 <td>A Filter to determine if the event should be handled by this Appender. More than one Filter
1933 may be used by using a CompositeFilter.</td>
1934 </tr>
1935 <tr>
1936 <td>layout</td>
1937 <td>Layout</td>
1938 <td>The Layout to use to format the LogEvent.</td>
1939 </tr>
1940 <tr>
1941 <td>Ssl</td>
1942 <td>SslConfiguration</td>
1943 <td>Contains the configuration for the KeyStore and TrustStore for https.
1944 Optional, uses Java runtime defaults if not specified. See <a href="#SSL">SSL</a></td>
1945 </tr>
1946 <tr>
1947 <td>verifyHostname</td>
1948 <td>boolean</td>
1949 <td>Whether to verify server hostname against certificate. Only valid for https.
1950 Optional, defaults to true</td>
1951 </tr>
1952 <tr>
1953 <td>url</td>
1954 <td>string</td>
1955 <td>The URL to use. The URL scheme must be "http" or "https".</td>
1956 </tr>
1957 <tr>
1958 <td>method</td>
1959 <td>string</td>
1960 <td>The HTTP method to use. Optional, default is "POST".</td>
1961 </tr>
1962 <tr>
1963 <td>connectTimeoutMillis</td>
1964 <td>integer</td>
1965 <td>The connect timeout in milliseconds. Optional, default is 0 (infinite timeout).</td>
1966 </tr>
1967 <tr>
1968 <td>readTimeoutMillis</td>
1969 <td>integer</td>
1970 <td>The socket read timeout in milliseconds. Optional, default is 0 (infinite timeout).</td>
1971 </tr>
1972 <tr>
1973 <td>headers</td>
1974 <td>Property[]</td>
1975 <td>Additional HTTP headers to use. The values support <a href="lookups.html">lookups</a>.</td>
1976 </tr>
1977 <tr>
1978 <td>ignoreExceptions</td>
1979 <td>boolean</td>
1980 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
1981 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
1982 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
1983 <a href="#FailoverAppender">FailoverAppender</a>.</td>
1984 </tr>
1985 </table>
1986 <p>
1987 Here is a sample HttpAppender configuration snippet:
1988 </p>
1989 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
1990 ...
1991 <Appenders>
1992 <Http name="Http" url="https://localhost:9200/test/log4j/">
1993 <Property name="X-Java-Runtime" value="$${java:runtime}" />
1994 <JsonLayout properties="true"/>
1995 <SSL>
1996 <KeyStore location="log4j2-keystore.jks" passwordEnvironmentVariable="KEYSTORE_PASSWORD"/>
1997 <TrustStore location="truststore.jks" passwordFile="${sys:user.home}/truststore.pwd"/>
1998 </SSL>
1999 </Http>
2000 </Appenders>]]></pre>
2001 </subsection>
2002 <a name="KafkaAppender"/>
2003 <subsection name="KafkaAppender">
2004 <p>
2005 The KafkaAppender logs events to an <a href="https://kafka.apache.org/">Apache Kafka</a> topic.
2006 Each log event is sent as a Kafka record.
2007 </p>
2008 <table>
2009 <caption align="top">KafkaAppender Parameters</caption>
2010 <tr>
2011 <th>Parameter Name</th>
2012 <th>Type</th>
2013 <th>Description</th>
2014 </tr>
2015 <tr>
2016 <td>topic</td>
2017 <td>String</td>
2018 <td>The Kafka topic to use. Required.</td>
2019 </tr>
2020 <tr>
2021 <td>key</td>
2022 <td>String</td>
2023 <td>The key that will be sent to Kafka with every message. Optional value defaulting to <code>null</code>.
2024 Any of the <a href="./lookups.html">Lookups</a>) can be included.
2025 </td>
2026 </tr>
2027 <tr>
2028 <td>filter</td>
2029 <td>Filter</td>
2030 <td>A Filter to determine if the event should be handled by this Appender. More than one Filter
2031 may be used by using a CompositeFilter.</td>
2032 </tr>
2033 <tr>
2034 <td>layout</td>
2035 <td>Layout</td>
2036 <td>
2037 The Layout to use to format the LogEvent. Required, there is no default.
2038 <em>New since 2.9, in previous versions <PatternLayout pattern="%m"/> was default.</em>
2039 </td>
2040 </tr>
2041 <tr>
2042 <td>name</td>
2043 <td>String</td>
2044 <td>The name of the Appender. Required.</td>
2045 </tr>
2046 <tr>
2047 <td>ignoreExceptions</td>
2048 <td>boolean</td>
2049 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
2050 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
2051 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
2052 <a href="#FailoverAppender">FailoverAppender</a>.</td>
2053 </tr>
2054 <tr>
2055 <td>syncSend</td>
2056 <td>boolean</td>
2057 <td>The default is <code>true</code>, causing sends to block until the record has been acknowledged by the
2058 Kafka server. When set to <code>false</code> sends return immediately, allowing for lower latency and significantly
2059 higher throughput. <i>New since 2.8. Be aware that this is a new addition, and it has not been extensively tested.
2060 Any failure sending to Kafka will be reported as error to StatusLogger and the log event will be dropped
2061 (the ignoreExceptions parameter will not be effective). Log events may arrive out of order to the Kafka server.</i>
2062 </td>
2063 </tr>
2064 <tr>
2065 <td>properties</td>
2066 <td>Property[]</td>
2067 <td>
2068 You can set properties in <a href="http://kafka.apache.org/documentation.html#producerconfigs">Kafka producer properties</a>.
2069 You need to set the <code>bootstrap.servers</code> property, there are sensible default values for the others.
2070 Do not set the <code>value.serializer</code> nor <code>key.serializer</code> properties.
2071 </td>
2072 </tr>
2073 </table>
2074 <p>
2075 Here is a sample KafkaAppender configuration snippet:
2076 </p>
2077 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
2078 ...
2079 <Appenders>
2080 <Kafka name="Kafka" topic="log-test">
2081 <PatternLayout pattern="%date %message"/>
2082 <Property name="bootstrap.servers">localhost:9092</Property>
2083 </Kafka>
2084 </Appenders>]]></pre>
2085 <p>
2086 This appender is synchronous by default and will block until the record has been acknowledged by the Kafka server, timeout
2087 for this can be set with the <code>timeout.ms</code> property (defaults to 30 seconds). Wrap with
2088 <a href="http://logging.apache.org/log4j/2.x/manual/appenders.html#AsyncAppender">Async appender</a> and/or set syncSend to
2089 <code>false</code> to log asynchronously.
2090 </p>
2091 <p>
2092 This appender requires the <a href="http://kafka.apache.org/">Kafka client library</a>. Note that you need to use a version of
2093 the Kafka client library matching the Kafka server used.
2094 </p>
2095 <p>
2096 <em>Note:</em>Make sure to not let <code>org.apache.kafka</code> log to a Kafka appender on DEBUG level,
2097 since that will cause recursive logging:
2098 </p>
2099 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
2100 ...
2101 <Loggers>
2102 <Root level="DEBUG">
2103 <AppenderRef ref="Kafka"/>
2104 </Root>
2105 <Logger name="org.apache.kafka" level="INFO" /> <!-- avoid recursive logging -->
2106 </Loggers>]]></pre>
2107 </subsection>
2108 <a name="MemoryMappedFileAppender" />
2109 <subsection name="MemoryMappedFileAppender">
2110 <p><i>New since 2.1. Be aware that this is a new addition, and although it has been
2111 tested on several platforms, it does not have as much track record as the other file appenders.</i></p>
2112 <p>
2113 The MemoryMappedFileAppender maps a part of the specified file into memory
2114 and writes log events to this memory, relying on the operating system's
2115 virtual memory manager to synchronize the changes to the storage device.
2116 The main benefit of using memory mapped files is I/O performance. Instead of making system
2117 calls to write to disk, this appender can simply change the program's local memory,
2118 which is orders of magnitude faster. Also, in most operating systems the memory
2119 region mapped actually is the kernel's <a href="http://en.wikipedia.org/wiki/Page_cache">page
2120 cache</a> (file cache), meaning that no copies need to be created in user space.
2121 (TODO: performance tests that compare performance of this appender to
2122 RandomAccessFileAppender and FileAppender.)
2123 </p>
2124 <p>
2125 There is some overhead with mapping a file region into memory,
2126 especially very large regions (half a gigabyte or more).
2127 The default region size is 32 MB, which should strike a reasonable balance
2128 between the frequency and the duration of remap operations.
2129 (TODO: performance test remapping various sizes.)
2130 </p>
2131 <p>
2132 Similar to the FileAppender and the RandomAccessFileAppender,
2133 MemoryMappedFileAppender uses a MemoryMappedFileManager to actually perform the
2134 file I/O. While MemoryMappedFileAppender from different Configurations
2135 cannot be shared, the MemoryMappedFileManagers can be if the Manager is
2136 accessible. For example, two web applications in a servlet container can have
2137 their own configuration and safely write to the same file if Log4j
2138 is in a ClassLoader that is common to both of them.
2139 </p>
2140 <table>
2141 <caption align="top">MemoryMappedFileAppender Parameters</caption>
2142 <tr>
2143 <th>Parameter Name</th>
2144 <th>Type</th>
2145 <th>Description</th>
2146 </tr>
2147 <tr>
2148 <td>append</td>
2149 <td>boolean</td>
2150 <td>When true - the default, records will be appended to the end
2151 of the file. When set to false, the file will be cleared before
2152 new records are written.
2153 </td>
2154 </tr>
2155 <tr>
2156 <td>fileName</td>
2157 <td>String</td>
2158 <td>The name of the file to write to. If the file, or any of its
2159 parent directories, do not exist, they will be created.
2160 </td>
2161 </tr>
2162 <tr>
2163 <td>filters</td>
2164 <td>Filter</td>
2165 <td>A Filter to determine if the event should be handled by this
2166 Appender. More than one Filter may be used by using a CompositeFilter.
2167 </td>
2168 </tr>
2169 <tr>
2170 <td>immediateFlush</td>
2171 <td>boolean</td>
2172 <td>
2173 <p>When set to true, each write will be followed by a
2174 call to <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/MappedByteBuffer.html#force()">MappedByteBuffer.force()</a>.
2175 This will guarantee the data is written to the storage device.
2176 </p>
2177 <p>The default for this parameter is <code>false</code>.
2178 This means that the data is written to the storage device even
2179 if the Java process crashes, but there may be data loss if the
2180 operating system crashes.</p>
2181 <p>Note that manually forcing a sync on every log event loses most
2182 of the performance benefits of using a memory mapped file.</p>
2183 <p>Flushing after every write is only useful when using this
2184 appender with synchronous loggers. Asynchronous loggers and
2185 appenders will automatically flush at the end of a batch of events,
2186 even if immediateFlush is set to false. This also guarantees
2187 the data is written to disk but is more efficient.
2188 </p>
2189 </td>
2190 </tr>
2191 <tr>
2192 <td>regionLength</td>
2193 <td>int</td>
2194 <td>The length of the mapped region, defaults to 32 MB
2195 (32 * 1024 * 1024 bytes). This parameter must be a value
2196 between 256 and 1,073,741,824 (1 GB or 2^30);
2197 values outside this range will be adjusted to the closest valid
2198 value.
2199 Log4j will round the specified value up to the nearest power of two.</td>
2200 </tr>
2201 <tr>
2202 <td>layout</td>
2203 <td>Layout</td>
2204 <td>The Layout to use to format the LogEvent. If no layout is supplied the default pattern layout
2205 of "%m%n" will be used.</td>
2206 </tr>
2207 <tr>
2208 <td>name</td>
2209 <td>String</td>
2210 <td>The name of the Appender.</td>
2211 </tr>
2212 <tr>
2213 <td>ignoreExceptions</td>
2214 <td>boolean</td>
2215 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
2216 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
2217 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
2218 <a href="#FailoverAppender">FailoverAppender</a>.</td>
2219 </tr>
2220 </table>
2221 <p>
2222 Here is a sample MemoryMappedFile configuration:
2223 </p>
2224
2225 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
2226 <Configuration status="warn" name="MyApp" packages="">
2227 <Appenders>
2228 <MemoryMappedFile name="MyFile" fileName="logs/app.log">
2229 <PatternLayout>
2230 <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
2231 </PatternLayout>
2232 </MemoryMappedFile>
2233 </Appenders>
2234 <Loggers>
2235 <Root level="error">
2236 <AppenderRef ref="MyFile"/>
2237 </Root>
2238 </Loggers>
2239 </Configuration>]]></pre>
2240 </subsection>
2241 <a name="NoSQLAppender"/>
2242 <subsection name="NoSQLAppender">
2243 <p>
2244 The NoSQLAppender writes log events to a NoSQL database using an internal lightweight provider interface.
2245 Provider implementations currently exist for MongoDB and Apache CouchDB, and writing a custom provider is
2246 quite simple.
2247 </p>
2248 <table>
2249 <caption align="top">NoSQLAppender Parameters</caption>
2250 <tr>
2251 <th>Parameter Name</th>
2252 <th>Type</th>
2253 <th>Description</th>
2254 </tr>
2255 <tr>
2256 <td>name</td>
2257 <td>String</td>
2258 <td><em>Required.</em> The name of the Appender.</td>
2259 </tr>
2260 <tr>
2261 <td>ignoreExceptions</td>
2262 <td>boolean</td>
2263 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
2264 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
2265 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
2266 <a href="#FailoverAppender">FailoverAppender</a>.</td>
2267 </tr>
2268 <tr>
2269 <td>filter</td>
2270 <td>Filter</td>
2271 <td>A Filter to determine if the event should be handled by this Appender. More than one Filter may be
2272 used by using a CompositeFilter.</td>
2273 </tr>
2274 <tr>
2275 <td>bufferSize</td>
2276 <td>int</td>
2277 <td>If an integer greater than 0, this causes the appender to buffer log events and flush whenever the
2278 buffer reaches this size.</td>
2279 </tr>
2280 <tr>
2281 <td>NoSqlProvider</td>
2282 <td>NoSQLProvider<C extends NoSQLConnection<W, T extends NoSQLObject<W>>></td>
2283 <td><em>Required.</em> The NoSQL provider that provides connections to the chosen NoSQL database.</td>
2284 </tr>
2285 </table>
2286 <p>You specify which NoSQL provider to use by specifying the appropriate configuration element within the
2287 <code><NoSql></code> element. The types currently supported are <code><MongoDb></code> and
2288 <code><CouchDb></code>. To create your own custom provider, read the JavaDoc for the
2289 <code>NoSQLProvider</code>, <code>NoSQLConnection</code>, and <code>NoSQLObject</code> classes and the
2290 documentation about creating Log4j plugins. We recommend you review the source code for the MongoDB and
2291 CouchDB providers as a guide for creating your own provider.
2292 </p>
2293 <p>
2294 The following example demonstrates how log events are persisted in NoSQL databases if represented in a JSON
2295 format:
2296 </p>
2297 <pre class="prettyprint lang-javascript"><![CDATA[{
2298 "level": "WARN",
2299 "loggerName": "com.example.application.MyClass",
2300 "message": "Something happened that you might want to know about.",
2301 "source": {
2302 "className": "com.example.application.MyClass",
2303 "methodName": "exampleMethod",
2304 "fileName": "MyClass.java",
2305 "lineNumber": 81
2306 },
2307 "marker": {
2308 "name": "SomeMarker",
2309 "parent" {
2310 "name": "SomeParentMarker"
2311 }
2312 },
2313 "threadName": "Thread-1",
2314 "millis": 1368844166761,
2315 "date": "2013-05-18T02:29:26.761Z",
2316 "thrown": {
2317 "type": "java.sql.SQLException",
2318 "message": "Could not insert record. Connection lost.",
2319 "stackTrace": [
2320 { "className": "org.example.sql.driver.PreparedStatement$1", "methodName": "responder", "fileName": "PreparedStatement.java", "lineNumber": 1049 },
2321 { "className": "org.example.sql.driver.PreparedStatement", "methodName": "executeUpdate", "fileName": "PreparedStatement.java", "lineNumber": 738 },
2322 { "className": "com.example.application.MyClass", "methodName": "exampleMethod", "fileName": "MyClass.java", "lineNumber": 81 },
2323 { "className": "com.example.application.MainClass", "methodName": "main", "fileName": "MainClass.java", "lineNumber": 52 }
2324 ],
2325 "cause": {
2326 "type": "java.io.IOException",
2327 "message": "Connection lost.",
2328 "stackTrace": [
2329 { "className": "java.nio.channels.SocketChannel", "methodName": "write", "fileName": null, "lineNumber": -1 },
2330 { "className": "org.example.sql.driver.PreparedStatement$1", "methodName": "responder", "fileName": "PreparedStatement.java", "lineNumber": 1032 },
2331 { "className": "org.example.sql.driver.PreparedStatement", "methodName": "executeUpdate", "fileName": "PreparedStatement.java", "lineNumber": 738 },
2332 { "className": "com.example.application.MyClass", "methodName": "exampleMethod", "fileName": "MyClass.java", "lineNumber": 81 },
2333 { "className": "com.example.application.MainClass", "methodName": "main", "fileName": "MainClass.java", "lineNumber": 52 }
2334 ]
2335 }
2336 },
2337 "contextMap": {
2338 "ID": "86c3a497-4e67-4eed-9d6a-2e5797324d7b",
2339 "username": "JohnDoe"
2340 },
2341 "contextStack": [
2342 "topItem",
2343 "anotherItem",
2344 "bottomItem"
2345 ]
2346 }]]></pre>
2347 </subsection>
2348 <a name="NoSQLAppenderMongoDB"/>
2349 <subsection name="NoSQLAppender for MongoDB">
2350 <p>
2351 Starting with Log4 2.11.0, we provide two MongoDB modules:
2352 </p>
2353 <ul>
2354 <li><code>log4j-mongodb2</code> defines the configuration element <a href="#NoSQLAppenderMongoDB2"><code>MongoDb2</code></a> matching the MongoDB Driver version 2.</li>
2355 <li><code>log4j-mongodb3</code> defines the configuration element <a href="#NoSQLAppenderMongoDB3"><code>MongoDb3</code></a> matching the MongoDB Driver version 3.</li>
2356 </ul>
2357 <p>
2358 We no longer provide the module <code>log4j-mongodb</code>.
2359 </p>
2360 <p>
2361 The module <code>log4j-mongodb2</code> aliases the old configuration element <code>MongoDb</code> to <a href="#NoSQLAppenderMongoDB2"><code>MongoDb2</code></a>.
2362 </p>
2363 </subsection>
2364 <a name="NoSQLAppenderMongoDB2"/>
2365 <subsection name="NoSQLAppender for MongoDB 2">
2366 <p>
2367 This section details specializations of the <a href="#NoSQLAppender">NoSQLAppender</a> provider for MongoDB using
2368 the MongoDB driver version 2. The NoSQLAppender Appender writes log events to a NoSQL database using an
2369 internal lightweight provider interface.
2370 </p>
2371 <table>
2372 <caption align="top">MongoDB2 Provider Parameters</caption>
2373 <tr>
2374 <th>Parameter Name</th>
2375 <th>Type</th>
2376 <th>Description</th>
2377 </tr>
2378 <tr>
2379 <td>collectionName</td>
2380 <td>String</td>
2381 <td><em>Required.</em> The name of the MongoDB collection to insert the events into.</td>
2382 </tr>
2383 <tr>
2384 <td>writeConcernConstant</td>
2385 <td>Field</td>
2386 <td>By default, the MongoDB provider inserts records with the instructions
2387 <code>com.mongodb.WriteConcern.ACKNOWLEDGED</code>. Use this optional attribute to specify the name of
2388 a constant other than <code>ACKNOWLEDGED</code>.</td>
2389 </tr>
2390 <tr>
2391 <td>writeConcernConstantClass</td>
2392 <td>Class</td>
2393 <td>If you specify <code>writeConcernConstant</code>, you can use this attribute to specify a class other
2394 than <code>com.mongodb.WriteConcern</code> to find the constant on (to create your own custom
2395 instructions).</td>
2396 </tr>
2397 <tr>
2398 <td>factoryClassName</td>
2399 <td>Class</td>
2400 <td>To provide a connection to the MongoDB database, you can use this attribute and
2401 <code>factoryMethodName</code> to specify a class and static method to get the connection from. The
2402 method must return a <code>com.mongodb.DB</code> or a <code>com.mongodb.MongoClient</code>. If the
2403 <code>DB</code> is not authenticated, you must also specify a <code>username</code> and
2404 <code>password</code>. If you use the factory method for providing a connection, you must not specify
2405 the <code>databaseName</code>, <code>server</code>, or <code>port</code> attributes.</td>
2406 </tr>
2407 <tr>
2408 <td>factoryMethodName</td>
2409 <td>Method</td>
2410 <td>See the documentation for attribute <code>factoryClassName</code>.</td>
2411 </tr>
2412 <tr>
2413 <td>databaseName</td>
2414 <td>String</td>
2415 <td>If you do not specify a <code>factoryClassName</code> and <code>factoryMethodName</code> for providing
2416 a MongoDB connection, you must specify a MongoDB database name using this attribute. You must also
2417 specify a <code>username</code> and <code>password</code>. You can optionally also specify a
2418 <code>server</code> (defaults to localhost), and a <code>port</code> (defaults to the default MongoDB
2419 port).</td>
2420 </tr>
2421 <tr>
2422 <td>server</td>
2423 <td>String</td>
2424 <td>See the documentation for attribute <code>databaseName</code>.</td>
2425 </tr>
2426 <tr>
2427 <td>port</td>
2428 <td>int</td>
2429 <td>See the documentation for attribute <code>databaseName</code>.</td>
2430 </tr>
2431 <tr>
2432 <td>username</td>
2433 <td>String</td>
2434 <td>See the documentation for attributes <code>databaseName</code> and <code>factoryClassName</code>.</td>
2435 </tr>
2436 <tr>
2437 <td>password</td>
2438 <td>String</td>
2439 <td>See the documentation for attributes <code>databaseName</code> and <code>factoryClassName</code>.</td>
2440 </tr>
2441 <tr>
2442 <td>capped</td>
2443 <td>boolean</td>
2444 <td>Enable support for <a href="https://docs.mongodb.com/manual/core/capped-collections/">capped collections</a></td>
2445 </tr>
2446 <tr>
2447 <td>collectionSize</td>
2448 <td>int</td>
2449 <td>Specify the size in bytes of the capped collection to use if enabled. The minimum size is 4096 bytes,
2450 and larger sizes will be increased to the nearest integer multiple of 256. See the capped collection documentation
2451 linked above for more information.</td>
2452 </tr>
2453 </table>
2454 <p>
2455 This appender is <a href="messages.html#MapMessage">MapMessage</a>-aware.
2456 </p>
2457 <p>
2458 Here are a few sample configurations for the NoSQLAppender and MongoDB2 provider:
2459 </p>
2460
2461 <pre class="prettyprint linenums lang-xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
2462 <Configuration status="error">
2463 <Appenders>
2464 <NoSql name="databaseAppender">
2465 <MongoDb2 databaseName="applicationDb" collectionName="applicationLog" server="mongo.example.org"
2466 username="loggingUser" password="abc123" />
2467 </NoSql>
2468 </Appenders>
2469 <Loggers>
2470 <Root level="warn">
2471 <AppenderRef ref="databaseAppender"/>
2472 </Root>
2473 </Loggers>
2474 </Configuration>]]></pre>
2475
2476 <pre class="prettyprint linenums lang-xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
2477 <Configuration status="error">
2478 <Appenders>
2479 <NoSql name="databaseAppender">
2480 <MongoDb2 collectionName="applicationLog" factoryClassName="org.example.db.ConnectionFactory"
2481 factoryMethodName="getNewMongoClient" />
2482 </NoSql>
2483 </Appenders>
2484 <Loggers>
2485 <Root level="warn">
2486 <AppenderRef ref="databaseAppender"/>
2487 </Root>
2488 </Loggers>
2489 </Configuration>]]></pre>
2490 <p>
2491 Starting in Log4j version 2.11.0, the provider element name is <code>MongoDb2</code>.
2492 The name <code>MongoDb</code> is now a deprecated alias for <code>MongoDb2</code>.
2493 </p>
2494 </subsection>
2495 <a name="NoSQLAppenderMongoDB3"/>
2496 <subsection name="NoSQLAppender for MongoDB 3">
2497 <p>
2498 This section details specializations of the <a href="#NoSQLAppender">NoSQLAppender</a> provider for MongoDB using
2499 the MongoDB driver version 3. The NoSQLAppender Appender writes log events to a NoSQL database using an
2500 internal lightweight provider interface.
2501 </p>
2502 <table>
2503 <caption align="top">MongoDB3 Provider Parameters</caption>
2504 <tr>
2505 <th>Parameter Name</th>
2506 <th>Type</th>
2507 <th>Description</th>
2508 </tr>
2509 <tr>
2510 <td>collectionName</td>
2511 <td>String</td>
2512 <td><em>Required.</em> The name of the MongoDB collection to insert the events into.</td>
2513 </tr>
2514 <tr>
2515 <td>writeConcernConstant</td>
2516 <td>Field</td>
2517 <td>By default, the MongoDB provider inserts records with the instructions
2518 <code>com.mongodb.WriteConcern.ACKNOWLEDGED</code>. Use this optional attribute to specify the name of
2519 a constant other than <code>ACKNOWLEDGED</code>.</td>
2520 </tr>
2521 <tr>
2522 <td>writeConcernConstantClass</td>
2523 <td>Class</td>
2524 <td>If you specify <code>writeConcernConstant</code>, you can use this attribute to specify a class other
2525 than <code>com.mongodb.WriteConcern</code> to find the constant on (to create your own custom
2526 instructions).</td>
2527 </tr>
2528 <tr>
2529 <td>factoryClassName</td>
2530 <td>Class</td>
2531 <td>To provide a connection to the MongoDB database, you can use this attribute and
2532 <code>factoryMethodName</code> to specify a class and static method to get the connection from. The
2533 method must return a <code>com.mongodb.client.MongoDatabase</code> or a <code>com.mongodb.MongoClient</code>. If the
2534 <code>com.mongodb.client.MongoDatabase</code> is not authenticated, you must also specify a <code>username</code> and
2535 <code>password</code>. If you use the factory method for providing a connection, you must not specify
2536 the <code>databaseName</code>, <code>server</code>, or <code>port</code> attributes.</td>
2537 </tr>
2538 <tr>
2539 <td>factoryMethodName</td>
2540 <td>Method</td>
2541 <td>See the documentation for attribute <code>factoryClassName</code>.</td>
2542 </tr>
2543 <tr>
2544 <td>databaseName</td>
2545 <td>String</td>
2546 <td>If you do not specify a <code>factoryClassName</code> and <code>factoryMethodName</code> for providing
2547 a MongoDB connection, you must specify a MongoDB database name using this attribute. You must also
2548 specify a <code>username</code> and <code>password</code>. You can optionally also specify a
2549 <code>server</code> (defaults to localhost), and a <code>port</code> (defaults to the default MongoDB
2550 port).</td>
2551 </tr>
2552 <tr>
2553 <td>server</td>
2554 <td>String</td>
2555 <td>See the documentation for attribute <code>databaseName</code>.</td>
2556 </tr>
2557 <tr>
2558 <td>port</td>
2559 <td>int</td>
2560 <td>See the documentation for attribute <code>databaseName</code>.</td>
2561 </tr>
2562 <tr>
2563 <td>username</td>
2564 <td>String</td>
2565 <td>See the documentation for attributes <code>databaseName</code> and <code>factoryClassName</code>.</td>
2566 </tr>
2567 <tr>
2568 <td>password</td>
2569 <td>String</td>
2570 <td>See the documentation for attributes <code>databaseName</code> and <code>factoryClassName</code>.</td>
2571 </tr>
2572 <tr>
2573 <td>capped</td>
2574 <td>boolean</td>
2575 <td>Enable support for <a href="https://docs.mongodb.com/manual/core/capped-collections/">capped collections</a></td>
2576 </tr>
2577 <tr>
2578 <td>collectionSize</td>
2579 <td>int</td>
2580 <td>Specify the size in bytes of the capped collection to use if enabled. The minimum size is 4096 bytes,
2581 and larger sizes will be increased to the nearest integer multiple of 256. See the capped collection documentation
2582 linked above for more information.</td>
2583 </tr>
2584 </table>
2585 <p>
2586 This appender is <a href="messages.html#MapMessage">MapMessage</a>-aware.
2587 </p>
2588 <p>
2589 Here are a few sample configurations for the NoSQLAppender and MongoDB3 provider:
2590 </p>
2591
2592 <pre class="prettyprint linenums lang-xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
2593 <Configuration status="error">
2594 <Appenders>
2595 <NoSql name="databaseAppender">
2596 <MongoDb3 databaseName="applicationDb" collectionName="applicationLog" server="mongo.example.org"
2597 username="loggingUser" password="abc123" />
2598 </NoSql>
2599 </Appenders>
2600 <Loggers>
2601 <Root level="warn">
2602 <AppenderRef ref="databaseAppender"/>
2603 </Root>
2604 </Loggers>
2605 </Configuration>]]></pre>
2606
2607 <pre class="prettyprint linenums lang-xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
2608 <Configuration status="error">
2609 <Appenders>
2610 <NoSql name="databaseAppender">
2611 <MongoDb3 collectionName="applicationLog" factoryClassName="org.example.db.ConnectionFactory"
2612 factoryMethodName="getNewMongoClient" />
2613 </NoSql>
2614 </Appenders>
2615 <Loggers>
2616 <Root level="warn">
2617 <AppenderRef ref="databaseAppender"/>
2618 </Root>
2619 </Loggers>
2620 </Configuration>]]></pre>
2621 </subsection>
2622 <a name="NoSQLAppenderApacheCouchDB"/>
2623 <subsection name="NoSQLAppender for Apache CouchDB">
2624 <p>
2625 This section details specializations of the <a href="#NoSQLAppender">NoSQLAppender</a> provider for CouchDB.
2626 The NoSQLAppender writes log events to a NoSQL database using an internal lightweight provider interface.
2627 </p>
2628 <table>
2629 <caption align="top">CouchDB Provider Parameters</caption>
2630 <tr>
2631 <th>Parameter Name</th>
2632 <th>Type</th>
2633 <th>Description</th>
2634 </tr>
2635 <tr>
2636 <td>factoryClassName</td>
2637 <td>Class</td>
2638 <td>To provide a connection to the CouchDB database, you can use this attribute and
2639 <code>factoryMethodName</code> to specify a class and static method to get the connection from. The
2640 method must return a <code>org.lightcouch.CouchDbClient</code> or a
2641 <code>org.lightcouch.CouchDbProperties</code>. If you use the factory method for providing a connection,
2642 you must not specify the <code>databaseName</code>, <code>protocol</code>, <code>server</code>,
2643 <code>port</code>, <code>username</code>, or <code>password</code> attributes.</td>
2644 </tr>
2645 <tr>
2646 <td>factoryMethodName</td>
2647 <td>Method</td>
2648 <td>See the documentation for attribute <code>factoryClassName</code>.</td>
2649 </tr>
2650 <tr>
2651 <td>databaseName</td>
2652 <td>String</td>
2653 <td>If you do not specify a <code>factoryClassName</code> and <code>factoryMethodName</code> for providing
2654 a CouchDB connection, you must specify a CouchDB database name using this attribute. You must also
2655 specify a <code>username</code> and <code>password</code>. You can optionally also specify a
2656 <code>protocol</code> (defaults to http), <code>server</code> (defaults to localhost), and a
2657 <code>port</code> (defaults to 80 for http and 443 for https).</td>
2658 </tr>
2659 <tr>
2660 <td>protocol</td>
2661 <td>String</td>
2662 <td>Must either be "http" or "https." See the documentation for attribute <code>databaseName</code>.</td>
2663 </tr>
2664 <tr>
2665 <td>server</td>
2666 <td>String</td>
2667 <td>See the documentation for attribute <code>databaseName</code>.</td>
2668 </tr>
2669 <tr>
2670 <td>port</td>
2671 <td>int</td>
2672 <td>See the documentation for attribute <code>databaseName</code>.</td>
2673 </tr>
2674 <tr>
2675 <td>username</td>
2676 <td>String</td>
2677 <td>See the documentation for attributes <code>databaseName</code>.</td>
2678 </tr>
2679 <tr>
2680 <td>password</td>
2681 <td>String</td>
2682 <td>See the documentation for attributes <code>databaseName</code>.</td>
2683 </tr>
2684 </table>
2685 <p>
2686 Here are a few sample configurations for the NoSQLAppender and CouchDB provider:
2687 </p>
2688
2689 <pre class="prettyprint linenums lang-xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
2690 <Configuration status="error">
2691 <Appenders>
2692 <NoSql name="databaseAppender">
2693 <CouchDb databaseName="applicationDb" protocol="https" server="couch.example.org"
2694 username="loggingUser" password="abc123" />
2695 </NoSql>
2696 </Appenders>
2697 <Loggers>
2698 <Root level="warn">
2699 <AppenderRef ref="databaseAppender"/>
2700 </Root>
2701 </Loggers>
2702 </Configuration>]]></pre>
2703 </subsection>
2704 <a name="OutputStreamAppender"/>
2705 <subsection name="OutputStreamAppender">
2706 <p>
2707 The OutputStreamAppender provides the base for many of the other Appenders such as the File and Socket
2708 appenders that write the event to an Output Stream. It cannot be directly configured. Support for
2709 immediateFlush and buffering is provided by the OutputStreamAppender. The OutputStreamAppender uses an
2710 OutputStreamManager to handle the actual I/O, allowing the stream to be shared by Appenders in multiple
2711 configurations.
2712 </p>
2713 </subsection>
2714 <a name="RandomAccessFileAppender" />
2715 <subsection name="RandomAccessFileAppender">
2716 <p>
2717 The RandomAccessFileAppender is similar to the standard
2718 <a href="#FileAppender">FileAppender</a>
2719 except it is always buffered (this cannot be switched off)
2720 and internally it uses a
2721 <tt>ByteBuffer + RandomAccessFile</tt>
2722 instead of a
2723 <tt>BufferedOutputStream</tt>.
2724 We saw a 20-200% performance improvement compared to
2725 FileAppender with "bufferedIO=true" in our
2726 <a href="../performance.html#whichAppender">measurements</a>.
2727 Similar to the FileAppender,
2728 RandomAccessFileAppender uses a RandomAccessFileManager to actually perform the
2729 file I/O. While RandomAccessFileAppender
2730 from different Configurations
2731 cannot be shared, the RandomAccessFileManagers can be if the Manager is
2732 accessible. For example, two web applications in a
2733 servlet container can have
2734 their own configuration and safely
2735 write to the same file if Log4j
2736 is in a ClassLoader that is common to
2737 both of them.
2738 </p>
2739 <table>
2740 <caption align="top">RandomAccessFileAppender Parameters</caption>
2741 <tr>
2742 <th>Parameter Name</th>
2743 <th>Type</th>
2744 <th>Description</th>
2745 </tr>
2746 <tr>
2747 <td>append</td>
2748 <td>boolean</td>
2749 <td>When true - the default, records will be appended to the end
2750 of the file. When set to false,
2751 the file will be cleared before
2752 new records are written.
2753 </td>
2754 </tr>
2755 <tr>
2756 <td>fileName</td>
2757 <td>String</td>
2758 <td>The name of the file to write to. If the file, or any of its
2759 parent directories, do not exist,
2760 they will be created.
2761 </td>
2762 </tr>
2763 <tr>
2764 <td>filters</td>
2765 <td>Filter</td>
2766 <td>A Filter to determine if the event should be handled by this
2767 Appender. More than one Filter
2768 may be used by using a CompositeFilter.
2769 </td>
2770 </tr>
2771 <tr>
2772 <td>immediateFlush</td>
2773 <td>boolean</td>
2774 <td>
2775 <p>
2776 When set to true - the default, each write will be followed by a flush.
2777 This will guarantee the data is written
2778 to disk but could impact performance.
2779 </p>
2780 <p>
2781 Flushing after every write is only useful when using this
2782 appender with synchronous loggers. Asynchronous loggers and
2783 appenders will automatically flush at the end of a batch of events,
2784 even if immediateFlush is set to false. This also guarantees
2785 the data is written to disk but is more efficient.
2786 </p>
2787 </td>
2788 </tr>
2789 <tr>
2790 <td>bufferSize</td>
2791 <td>int</td>
2792 <td>The buffer size, defaults to 262,144 bytes (256 * 1024).</td>
2793 </tr>
2794 <tr>
2795 <td>layout</td>
2796 <td>Layout</td>
2797 <td>The Layout to use to format the LogEvent. If no layout is supplied the default pattern layout
2798 of "%m%n" will be used.</td>
2799 </tr>
2800 <tr>
2801 <td>name</td>
2802 <td>String</td>
2803 <td>The name of the Appender.</td>
2804 </tr>
2805 <tr>
2806 <td>ignoreExceptions</td>
2807 <td>boolean</td>
2808 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
2809 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
2810 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
2811 <a href="#FailoverAppender">FailoverAppender</a>.</td>
2812 </tr>
2813 </table>
2814 <p>
2815 Here is a sample RandomAccessFile configuration:
2816 </p>
2817
2818 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
2819 <Configuration status="warn" name="MyApp" packages="">
2820 <Appenders>
2821 <RandomAccessFile name="MyFile" fileName="logs/app.log">
2822 <PatternLayout>
2823 <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
2824 </PatternLayout>
2825 </RandomAccessFile>
2826 </Appenders>
2827 <Loggers>
2828 <Root level="error">
2829 <AppenderRef ref="MyFile"/>
2830 </Root>
2831 </Loggers>
2832 </Configuration>]]></pre>
2833 </subsection>
2834 <a name="RewriteAppender"/>
2835 <subsection name="RewriteAppender">
2836 <p>
2837 The RewriteAppender allows the LogEvent to manipulated before it is processed by another Appender. This
2838 can be used to mask sensitive information such as passwords or to inject information into each event.
2839 The RewriteAppender must be configured with a <a href="RewritePolicy">RewritePolicy</a>. The
2840 RewriteAppender should be configured after any Appenders it references to allow it to shut down properly.
2841 </p>
2842 <table>
2843 <caption align="top">RewriteAppender Parameters</caption>
2844 <tr>
2845 <th>Parameter Name</th>
2846 <th>Type</th>
2847 <th>Description</th>
2848 </tr>
2849 <tr>
2850 <td>AppenderRef</td>
2851 <td>String</td>
2852 <td>The name of the Appenders to call after the LogEvent has been manipulated. Multiple AppenderRef
2853 elements can be configured.</td>
2854 </tr>
2855 <tr>
2856 <td>filter</td>
2857 <td>Filter</td>
2858 <td>A Filter to determine if the event should be handled by this Appender. More than one Filter
2859 may be used by using a CompositeFilter.</td>
2860 </tr>
2861 <tr>
2862 <td>name</td>
2863 <td>String</td>
2864 <td>The name of the Appender.</td>
2865 </tr>
2866 <tr>
2867 <td>rewritePolicy</td>
2868 <td>RewritePolicy</td>
2869 <td>The RewritePolicy that will manipulate the LogEvent.</td>
2870 </tr>
2871 <tr>
2872 <td>ignoreExceptions</td>
2873 <td>boolean</td>
2874 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
2875 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
2876 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
2877 <a href="#FailoverAppender">FailoverAppender</a>.</td>
2878 </tr>
2879 </table>
2880 <h4>RewritePolicy</h4>
2881 <p>
2882 RewritePolicy is an interface that allows implementations to inspect and possibly modify LogEvents
2883 before they are passed to Appender. RewritePolicy declares a single method named rewrite that must
2884 be implemented. The method is passed the LogEvent and can return the same event or create a new one.
2885 </p>
2886 <h5>MapRewritePolicy</h5>
2887 <p>
2888 MapRewritePolicy will evaluate LogEvents that contain a MapMessage and will add or update
2889 elements of the Map.
2890 </p>
2891 <table>
2892 <tr>
2893 <th>Parameter Name</th>
2894 <th>Type</th>
2895 <th>Description</th>
2896 </tr>
2897 <tr>
2898 <td>mode</td>
2899 <td>String</td>
2900 <td>"Add" or "Update"</td>
2901 </tr>
2902 <tr>
2903 <td>keyValuePair</td>
2904 <td>KeyValuePair[]</td>
2905 <td>An array of keys and their values.</td>
2906 </tr>
2907 </table>
2908 <p>
2909 The following configuration shows a RewriteAppender configured to add a product key and its value
2910 to the MapMessage.:
2911 </p>
2912
2913 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
2914 <Configuration status="warn" name="MyApp" packages="">
2915 <Appenders>
2916 <Console name="STDOUT" target="SYSTEM_OUT">
2917 <PatternLayout pattern="%m%n"/>
2918 </Console>
2919 <Rewrite name="rewrite">
2920 <AppenderRef ref="STDOUT"/>
2921 <MapRewritePolicy mode="Add">
2922 <KeyValuePair key="product" value="TestProduct"/>
2923 </MapRewritePolicy>
2924 </Rewrite>
2925 </Appenders>
2926 <Loggers>
2927 <Root level="error">
2928 <AppenderRef ref="Rewrite"/>
2929 </Root>
2930 </Loggers>
2931 </Configuration>]]></pre>
2932 <h5>PropertiesRewritePolicy</h5>
2933 <p>
2934 PropertiesRewritePolicy will add properties configured on the policy to the ThreadContext Map
2935 being logged. The properties will not be added to the actual ThreadContext Map. The property
2936 values may contain variables that will be evaluated when the configuration is processed as
2937 well as when the event is logged.
2938 </p>
2939 <table>
2940 <tr>
2941 <th>Parameter Name</th>
2942 <th>Type</th>
2943 <th>Description</th>
2944 </tr>
2945 <tr>
2946 <td>properties</td>
2947 <td>Property[]</td>
2948 <td>One of more Property elements to define the keys and values to be added to the ThreadContext Map.</td>
2949 </tr>
2950 </table>
2951 <p>
2952 The following configuration shows a RewriteAppender configured to add a product key and its value
2953 to the MapMessage:
2954 </p>
2955 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
2956 <Configuration status="warn" name="MyApp" packages="">
2957 <Appenders>
2958 <Console name="STDOUT" target="SYSTEM_OUT">
2959 <PatternLayout pattern="%m%n"/>
2960 </Console>
2961 <Rewrite name="rewrite">
2962 <AppenderRef ref="STDOUT"/>
2963 <PropertiesRewritePolicy>
2964 <Property name="user">${sys:user.name}</Property>
2965 <Property name="env">${sys:environment}</Property>
2966 </PropertiesRewritePolicy>
2967 </Rewrite>
2968 </Appenders>
2969 <Loggers>
2970 <Root level="error">
2971 <AppenderRef ref="Rewrite"/>
2972 </Root>
2973 </Loggers>
2974 </Configuration>]]></pre>
2975 <h5>LoggerNameLevelRewritePolicy</h5>
2976 <p>
2977 You can use this policy to make loggers in third party code less chatty by changing event levels.
2978 The LoggerNameLevelRewritePolicy will rewrite log event levels for a given logger name prefix.
2979 You configure a LoggerNameLevelRewritePolicy with a logger name prefix and a pairs of levels,
2980 where a pair defines a source level and a target level.
2981 </p>
2982 <table>
2983 <tr>
2984 <th>Parameter Name</th>
2985 <th>Type</th>
2986 <th>Description</th>
2987 </tr>
2988 <tr>
2989 <td>logger</td>
2990 <td>String</td>
2991 <td>A logger name used as a prefix to test each event's logger name.</td>
2992 </tr>
2993 <tr>
2994 <td>LevelPair</td>
2995 <td>KeyValuePair[]</td>
2996 <td>An array of keys and their values, each key is a source level, each value a target level.</td>
2997 </tr>
2998 </table>
2999 <p>
3000 The following configuration shows a RewriteAppender configured to map level INFO to DEBUG and level
3001 WARN to INFO for all loggers that start with <code>com.foo.bar</code>.
3002 </p>
3003 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
3004 <Configuration status="warn" name="MyApp">
3005 <Appenders>
3006 <Console name="STDOUT" target="SYSTEM_OUT">
3007 <PatternLayout pattern="%m%n"/>
3008 </Console>
3009 <Rewrite name="rewrite">
3010 <AppenderRef ref="STDOUT"/>
3011 <LoggerNameLevelRewritePolicy logger="com.foo.bar">
3012 <KeyValuePair key="INFO" value="DEBUG"/>
3013 <KeyValuePair key="WARN" value="INFO"/>
3014 </LoggerNameLevelRewritePolicy>
3015 </Rewrite>
3016 </Appenders>
3017 <Loggers>
3018 <Root level="error">
3019 <AppenderRef ref="Rewrite"/>
3020 </Root>
3021 </Loggers>
3022 </Configuration>]]></pre>
3023 </subsection>
3024 <a name="RollingFileAppender"/>
3025 <subsection name="RollingFileAppender">
3026 <p>The RollingFileAppender is an OutputStreamAppender that writes to the File named in the fileName parameter
3027 and rolls the file over according the TriggeringPolicy and the RolloverPolicy. The
3028 RollingFileAppender uses a RollingFileManager (which extends OutputStreamManager) to actually perform the
3029 file I/O and perform the rollover. While RolloverFileAppenders from different Configurations cannot be
3030 shared, the RollingFileManagers can be if the Manager is accessible. For example, two web applications in a
3031 servlet container can have their own configuration and safely
3032 write to the same file if Log4j is in a ClassLoader that is common to both of them.</p>
3033 <p>
3034 A RollingFileAppender requires a <a href="#TriggeringPolicies">TriggeringPolicy</a> and a
3035 <a href="#RolloverStrategies">RolloverStrategy</a>. The triggering policy determines if a rollover should
3036 be performed while the RolloverStrategy defines how the rollover should be done. If no RolloverStrategy
3037 is configured, RollingFileAppender will use the <a href="#DefaultRolloverStrategy">DefaultRolloverStrategy</a>.
3038 Since log4j-2.5, a <a href="#CustomDeleteOnRollover">custom delete action</a> can be configured in the
3039 DefaultRolloverStrategy to run at rollover. Since 2.8 if no file name is configured then
3040 <a href="#DirectWriteRolloverStrategy">DirectWriteRolloverStrategy</a> will be used instead of
3041 DefaultRolloverStrategy.
3042 Since log4j-2.9, a <a href="#CustomPosixViewAttributeOnRollover">custom POSIX file attribute view action</a> can be configured in the
3043 DefaultRolloverStrategy to run at rollover, if not defined, inherited POSIX file attribute view from the RollingFileAppender will be applied.
3044 </p>
3045 <p>
3046 File locking is not supported by the RollingFileAppender.
3047 </p>
3048 <table>
3049 <caption align="top">RollingFileAppender Parameters</caption>
3050 <tr>
3051 <th>Parameter Name</th>
3052 <th>Type</th>
3053 <th>Description</th>
3054 </tr>
3055 <tr>
3056 <td>append</td>
3057 <td>boolean</td>
3058 <td>When true - the default, records will be appended to the end of the file. When set to false,
3059 the file will be cleared before new records are written.</td>
3060 </tr>
3061 <tr>
3062 <td>bufferedIO</td>
3063 <td>boolean</td>
3064 <td>When true - the default, records will be written to a buffer and the data will be written to
3065 disk when the buffer is full or, if immediateFlush is set, when the record is written.
3066 File locking cannot be used with bufferedIO. Performance tests have shown that using buffered I/O
3067 significantly improves performance, even if immediateFlush is enabled.</td>
3068 </tr>
3069 <tr>
3070 <td>bufferSize</td>
3071 <td>int</td>
3072 <td>When bufferedIO is true, this is the buffer size, the default is 8192 bytes.</td>
3073 </tr>
3074 <tr>
3075 <td>createOnDemand</td>
3076 <td>boolean</td>
3077 <td>The appender creates the file on-demand. The appender only creates the file when a log event
3078 passes all filters and is routed to this appender. Defaults to false.</td>
3079 </tr>
3080 <tr>
3081 <td>filter</td>
3082 <td>Filter</td>
3083 <td>A Filter to determine if the event should be handled by this Appender. More than one Filter
3084 may be used by using a CompositeFilter.</td>
3085 </tr>
3086 <tr>
3087 <td>fileName</td>
3088 <td>String</td>
3089 <td>The name of the file to write to. If the file, or any of its parent directories, do not exist,
3090 they will be created.</td>
3091 </tr>
3092 <tr>
3093 <td>filePattern</td>
3094 <td>String</td>
3095 <td>The pattern of the file name of the archived log file. The format of the pattern is
3096 dependent on the RolloverPolicy that is used. The DefaultRolloverPolicy will accept both
3097 a date/time pattern compatible with
3098 <a href="http://download.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat</a>
3099 and/or a %i which represents an integer counter. The pattern also supports interpolation at
3100 runtime so any of the Lookups (such as the <a href="./lookups.html#DateLookup">DateLookup</a>) can
3101 be included in the pattern.</td>
3102 </tr>
3103 <tr>
3104 <td>immediateFlush</td>
3105 <td>boolean</td>
3106 <td><p>When set to true - the default, each write will be followed by a flush.
3107 This will guarantee the data is written
3108 to disk but could impact performance.</p>
3109 <p>Flushing after every write is only useful when using this
3110 appender with synchronous loggers. Asynchronous loggers and
3111 appenders will automatically flush at the end of a batch of events,
3112 even if immediateFlush is set to false. This also guarantees
3113 the data is written to disk but is more efficient.</p>
3114 </td>
3115 </tr>
3116 <tr>
3117 <td>layout</td>
3118 <td>Layout</td>
3119 <td>The Layout to use to format the LogEvent. If no layout is supplied the default pattern layout
3120 of "%m%n" will be used.</td>
3121 </tr>
3122
3123 <tr>
3124 <td>name</td>
3125 <td>String</td>
3126 <td>The name of the Appender.</td>
3127 </tr>
3128 <tr>
3129 <td>policy</td>
3130 <td>TriggeringPolicy</td>
3131 <td>The policy to use to determine if a rollover should occur.</td>
3132 </tr>
3133 <tr>
3134 <td>strategy</td>
3135 <td>RolloverStrategy</td>
3136 <td>The strategy to use to determine the name and location of the archive file.</td>
3137 </tr>
3138 <tr>
3139 <td>ignoreExceptions</td>
3140 <td>boolean</td>
3141 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
3142 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
3143 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
3144 <a href="#FailoverAppender">FailoverAppender</a>.</td>
3145 </tr>
3146 <tr>
3147 <td>filePermissions</td>
3148 <td>String</td>
3149 <td><p>File attribute permissions in POSIX format to apply whenever the file is created.</p>
3150 <p>Underlying files system shall support <a class="javadoc" href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/PosixFileAttributeView.html">POSIX</a> file attribute view.</p>
3151 <p>Examples: rw------- or rw-rw-rw- etc...</p></td>
3152 </tr>
3153 <tr>
3154 <td>fileOwner</td>
3155 <td>String</td>
3156 <td><p>File owner to define whenever the file is created.</p>
3157 <p>Changing file's owner may be restricted for security reason and Operation not permitted IOException thrown.
3158 Only processes with an effective user ID equal to the user ID
3159 of the file or with appropriate privileges may change the ownership of a file
3160 if <a href="http://www.gnu.org/software/libc/manual/html_node/Options-for-Files.html">_POSIX_CHOWN_RESTRICTED</a> is in effect for path.</p>
3161 <p>Underlying files system shall support file <a class="javadoc" href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/FileOwnerAttributeView.html">owner</a> attribute view.</p>
3162 </td>
3163 </tr>
3164 <tr>
3165 <td>fileGroup</td>
3166 <td>String</td>
3167 <td><p>File group to define whenever the file is created.</p>
3168 <p>Underlying files system shall support <a class="javadoc" href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/PosixFileAttributeView.html">POSIX</a> file attribute view.</p>
3169 </td>
3170 </tr>
3171 </table>
3172 <a name="TriggeringPolicies"/>
3173 <h4>Triggering Policies</h4>
3174 <h5>Composite Triggering Policy</h5>
3175 <p>
3176 The <code>CompositeTriggeringPolicy</code> combines multiple triggering policies and returns true if
3177 any of the configured policies return true. The <code>CompositeTriggeringPolicy</code> is configured
3178 simply by wrapping other policies in a <code>Policies</code> element.
3179 </p>
3180 <p>
3181 For example, the following XML fragment defines policies that rollover the log when the JVM starts,
3182 when the log size reaches twenty megabytes, and when the current date no longer matches the log’s
3183 start date.
3184 </p>
3185 <pre class="prettyprint linenums"><![CDATA[<Policies>
3186 <OnStartupTriggeringPolicy />
3187 <SizeBasedTriggeringPolicy size="20 MB" />
3188 <TimeBasedTriggeringPolicy />
3189 </Policies>]]></pre>
3190 <h5>Cron Triggering Policy</h5>
3191 <p>The <code>CronTriggeringPolicy</code> triggers rollover based on a cron expression. This policy
3192 is controlled by a timer and is asynchronous to processing log events, so it is possible that log events
3193 from the previous or next time period may appear at the beginning or end of the log file. The
3194 filePattern attribute of the Appender should contain a timestamp otherwise the target file will be
3195 overwritten on each rollover.
3196 </p>
3197 <table>
3198 <caption align="top">CronTriggeringPolicy Parameters</caption>
3199 <tr>
3200 <th>Parameter Name</th>
3201 <th>Type</th>
3202 <th>Description</th>
3203 </tr>
3204 <tr>
3205 <td>schedule</td>
3206 <td>String</td>
3207 <td>The cron expression. The expression is the same as what is allowed in the Quartz scheduler. See
3208 <a href="../log4j-core/apidocs/org/apache/logging/log4j/core/util/CronExpression.html">CronExpression</a>
3209 for a full description of the expression.
3210 </td>
3211 </tr>
3212 <tr>
3213 <td>evaluateOnStartup</td>
3214 <td>boolean</td>
3215 <td>On startup the cron expression will be evaluated against the file's last modification timestamp.
3216 If the cron expression indicates a rollover should have occurred between that time and the current
3217 time the file will be immediately rolled over.</td>
3218 </tr>
3219 </table>
3220 <h5>OnStartup Triggering Policy</h5>
3221 <p>
3222 The <code>OnStartupTriggeringPolicy</code> policy causes a rollover if the log file is older than the
3223 current JVM's start time and the minimum file size is met or exceeded.
3224 </p>
3225 <table>
3226 <caption align="top">OnStartupTriggeringPolicy Parameters</caption>
3227 <tr>
3228 <th>Parameter Name</th>
3229 <th>Type</th>
3230 <th>Description</th>
3231 </tr>
3232 <tr>
3233 <td>minSize</td>
3234 <td>long</td>
3235 <td>
3236 The minimum size the file must have to roll over. A size of zero will cause a roll over no matter
3237 what the file size is. The default value is 1, which will prevent rolling over an empty file.
3238 </td>
3239 </tr>
3240 </table>
3241 <p>
3242 <em>Google App Engine note:</em><br />
3243 When running in Google App Engine, the OnStartup policy causes a rollover if the log file is older
3244 than <em>the time when Log4J initialized</em>.
3245 (Google App Engine restricts access to certain classes so Log4J cannot determine JVM start time with
3246 <code>java.lang.management.ManagementFactory.getRuntimeMXBean().getStartTime()</code>
3247 and falls back to Log4J initialization time instead.)
3248 </p>
3249 <h5>SizeBased Triggering Policy</h5>
3250 <p>
3251 The <code>SizeBasedTriggeringPolicy</code> causes a rollover once the file has reached the specified
3252 size. The size can be specified in bytes, with the suffix KB, MB or GB, for example <code>20MB</code>.
3253 When combined with a time based triggering policy the file pattern must contain a <code>%i</code>
3254 otherwise the target file will be overwritten on every rollover as the SizeBased Triggering Policy
3255 will not cause the timestamp value in the file name to change. When used without a time based
3256 triggering policy the SizeBased Triggering Policy will cause the timestamp value to change.
3257 </p>
3258 <h5>TimeBased Triggering Policy</h5>
3259 <p>
3260 The <code>TimeBasedTriggeringPolicy</code> causes a rollover once the date/time pattern no longer
3261 applies to the active file. This policy accepts an <code>interval</code> attribute which indicates how
3262 frequently the rollover should occur based on the time pattern and a <code>modulate</code> boolean
3263 attribute.
3264 </p>
3265 <table>
3266 <caption align="top">TimeBasedTriggeringPolicy Parameters</caption>
3267 <tr>
3268 <th>Parameter Name</th>
3269 <th>Type</th>
3270 <th>Description</th>
3271 </tr>
3272 <tr>
3273 <td>interval</td>
3274 <td>integer</td>
3275 <td>How often a rollover should occur based on the most specific time unit in the date pattern.
3276 For example, with a date pattern with hours as the most specific item and and increment of 4 rollovers
3277 would occur every 4 hours.
3278 The default value is 1.</td>
3279 </tr>
3280 <tr>
3281 <td>modulate</td>
3282 <td>boolean</td>
3283 <td>Indicates whether the interval should be adjusted to cause the next rollover to occur on
3284 the interval boundary. For example, if the item is hours, the current hour is 3 am and the
3285 interval is 4 then the first rollover will occur at 4 am and then next ones will occur at
3286 8 am, noon, 4pm, etc.</td>
3287 </tr>
3288 <tr>
3289 <td>maxRandomDelay</td>
3290 <td>integer</td>
3291 <td>Indicates the maximum number of seconds to randomly delay a rollover. By default,
3292 this is 0 which indicates no delay. This setting is useful on servers where multiple
3293 applications are configured to rollover log files at the same time and can spread
3294 the load of doing so across time.</td>
3295 </tr>
3296 </table>
3297 <a name="RolloverStrategies"/>
3298 <h4>Rollover Strategies</h4>
3299 <a name="DefaultRolloverStrategy"/>
3300 <h5>Default Rollover Strategy</h5>
3301 <p>
3302 The default rollover strategy accepts both a date/time pattern and an integer from the filePattern
3303 attribute specified on the RollingFileAppender itself. If the date/time pattern
3304 is present it will be replaced with the current date and time values. If the pattern contains an integer
3305 it will be incremented on each rollover. If the pattern contains both a date/time and integer
3306 in the pattern the integer will be incremented until the result of the date/time pattern changes. If
3307 the file pattern ends with ".gz", ".zip", ".bz2", ".deflate", ".pack200", or ".xz" the resulting archive
3308 will be compressed using the compression scheme that matches the suffix. The formats bzip2, Deflate,
3309 Pack200 and XZ require <a href="http://commons.apache.org/proper/commons-compress/">Apache Commons Compress</a>.
3310 In addition, XZ requires <a href="http://tukaani.org/xz/java.html">XZ for Java</a>.
3311 The pattern may also contain lookup references that can be resolved at runtime such as is shown in the example
3312 below.
3313 </p>
3314 <p>The default rollover strategy supports three variations for incrementing
3315 the counter. To illustrate how it works, suppose that the min attribute
3316 is set to 1, the max attribute is set to 3, the file name is "foo.log",
3317 and the file name pattern is "foo-%i.log".
3318 </p>
3319
3320 <table>
3321 <tr>
3322 <th>Number of rollovers</th>
3323 <th>Active output target</th>
3324 <th>Archived log files</th>
3325 <th>Description</th>
3326 </tr>
3327 <tr>
3328 <td>0</td>
3329 <td>foo.log</td>
3330 <td>-</td>
3331 <td>All logging is going to the initial file.</td>
3332 </tr>
3333 <tr>
3334 <td>1</td>
3335 <td>foo.log</td>
3336 <td>foo-1.log</td>
3337 <td>During the first rollover foo.log is renamed to foo-1.log. A new foo.log file is created and
3338 starts being written to.</td>
3339 </tr>
3340 <tr>
3341 <td>2</td>
3342 <td>foo.log</td>
3343 <td>foo-2.log, foo-1.log</td>
3344 <td>During the second rollover foo.log is renamed to foo-2.log. A new foo.log file is created and
3345 starts being written to.</td>
3346 </tr>
3347 <tr>
3348 <td>3</td>
3349 <td>foo.log</td>
3350 <td>foo-3.log, foo-2.log, foo-1.log</td>
3351 <td>During the third rollover foo.log is renamed to foo-3.log. A new foo.log file is created and
3352 starts being written to.</td>
3353 </tr>
3354 <tr>
3355 <td>4</td>
3356 <td>foo.log</td>
3357 <td>foo-3.log, foo-2.log, foo-1.log</td>
3358 <td>In the fourth and subsequent rollovers, foo-1.log is deleted, foo-2.log is renamed to
3359 foo-1.log, foo-3.log is renamed to foo-2.log and foo.log is renamed to
3360 foo-3.log. A new foo.log file is created and starts being written to.</td>
3361 </tr>
3362 </table>
3363 <p>By way of contrast, when the fileIndex attribute is set to "min" but all the other settings are the
3364 same the "fixed window" strategy will be performed.
3365 </p>
3366 <table>
3367 <tr>
3368 <th>Number of rollovers</th>
3369 <th>Active output target</th>
3370 <th>Archived log files</th>
3371 <th>Description</th>
3372 </tr>
3373 <tr>
3374 <td>0</td>
3375 <td>foo.log</td>
3376 <td>-</td>
3377 <td>All logging is going to the initial file.</td>
3378 </tr>
3379 <tr>
3380 <td>1</td>
3381 <td>foo.log</td>
3382 <td>foo-1.log</td>
3383 <td>During the first rollover foo.log is renamed to foo-1.log. A new foo.log file is created and
3384 starts being written to.</td>
3385 </tr>
3386 <tr>
3387 <td>2</td>
3388 <td>foo.log</td>
3389 <td>foo-1.log, foo-2.log</td>
3390 <td>During the second rollover foo-1.log is renamed to foo-2.log and foo.log is renamed to
3391 foo-1.log. A new foo.log file is created and starts being written to.</td>
3392 </tr>
3393 <tr>
3394 <td>3</td>
3395 <td>foo.log</td>
3396 <td>foo-1.log, foo-2.log, foo-3.log</td>
3397 <td>During the third rollover foo-2.log is renamed to foo-3.log, foo-1.log is renamed to foo-2.log and
3398 foo.log is renamed to foo-1.log. A new foo.log file is created and starts being written to.</td>
3399 </tr>
3400 <tr>
3401 <td>4</td>
3402 <td>foo.log</td>
3403 <td>foo-1.log, foo-2.log, foo-3.log</td>
3404 <td>In the fourth and subsequent rollovers, foo-3.log is deleted, foo-2.log is renamed to
3405 foo-3.log, foo-1.log is renamed to foo-2.log and foo.log is renamed to
3406 foo-1.log. A new foo.log file is created and starts being written to.</td>
3407 </tr>
3408 </table>
3409 <p>
3410 Finally, as of release 2.8, if the fileIndex attribute is set to "nomax" then the min and max values
3411 will be ignored and file numbering will increment by 1 and each rollover will have an incrementally
3412 higher value with no maximum number of files.
3413 </p>
3414 <table>
3415 <caption align="top">DefaultRolloverStrategy Parameters</caption>
3416 <tr>
3417 <th>Parameter Name</th>
3418 <th>Type</th>
3419 <th>Description</th>
3420 </tr>
3421 <tr>
3422 <td>fileIndex</td>
3423 <td>String</td>
3424 <td>If set to "max" (the default), files with a higher index will be newer than files with a
3425 smaller index. If set to "min", file renaming and the counter will follow the Fixed Window strategy
3426 described above.</td>
3427 </tr>
3428 <tr>
3429 <td>min</td>
3430 <td>integer</td>
3431 <td>The minimum value of the counter. The default value is 1.</td>
3432 </tr>
3433 <tr>
3434 <td>max</td>
3435 <td>integer</td>
3436 <td>The maximum value of the counter. Once this values is reached older archives will be
3437 deleted on subsequent rollovers. The default value is 7.</td>
3438 </tr>
3439 <tr>
3440 <td>compressionLevel</td>
3441 <td>integer</td>
3442 <td>
3443 Sets the compression level, 0-9, where 0 = none, 1 = best speed, through 9 = best compression.
3444 Only implemented for ZIP files.
3445 </td>
3446 </tr>
3447 <tr>
3448 <td>tempCompressedFilePattern</td>
3449 <td>String</td>
3450 <td>The pattern of the file name of the archived log file during compression.</td>
3451 </tr>
3452 </table>
3453 <a name="DirectWriteRolloverStrategy"/>
3454 <h5>DirectWrite Rollover Strategy</h5>
3455 <p>
3456 The DirectWriteRolloverStrategy causes log events to be written directly to files represented by the
3457 file pattern. With this strategy file renames are not performed. If the size-based triggering policy
3458 causes multiple files to be written durring the specified time period they will be numbered starting
3459 at one and continually incremented until a time-based rollover occurs.
3460 </p>
3461 <p>
3462 Warning: If the file pattern has a
3463 suffix indicating compression should take place the current file will not be compressed when the
3464 application is shut down. Furthermore, if the time changes such that the file pattern no longer
3465 matches the current file it will not be compressed at startup either.
3466 </p>
3467 <table>
3468 <caption align="top">DirectWriteRolloverStrategy Parameters</caption>
3469 <tr>
3470 <th>Parameter Name</th>
3471 <th>Type</th>
3472 <th>Description</th>
3473 </tr>
3474 <tr>
3475 <td>maxFiles</td>
3476 <td>String</td>
3477 <td>The maximum number of files to allow in the time period matching the file pattern. If the
3478 number of files is exceeded the oldest file will be deleted. If specified, the value must
3479 be greater than 1. If the value is less than zero or omitted then the number of files will
3480 not be limited.</td>
3481 </tr>
3482 <tr>
3483 <td>compressionLevel</td>
3484 <td>integer</td>
3485 <td>
3486 Sets the compression level, 0-9, where 0 = none, 1 = best speed, through 9 = best compression.
3487 Only implemented for ZIP files.
3488 </td>
3489 </tr>
3490 <tr>
3491 <td>tempCompressedFilePattern</td>
3492 <td>String</td>
3493 <td>The pattern of the file name of the archived log file during compression.</td>
3494 </tr>
3495 </table>
3496 <p>
3497 Below is a sample configuration that uses a RollingFileAppender with both the time and size based
3498 triggering policies, will create up to 7 archives on the same day (1-7) that are stored in a directory
3499 based on the current year and month, and will compress each
3500 archive using gzip:
3501 </p>
3502
3503 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
3504 <Configuration status="warn" name="MyApp" packages="">
3505 <Appenders>
3506 <RollingFile name="RollingFile" fileName="logs/app.log"
3507 filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
3508 <PatternLayout>
3509 <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
3510 </PatternLayout>
3511 <Policies>
3512 <TimeBasedTriggeringPolicy />
3513 <SizeBasedTriggeringPolicy size="250 MB"/>
3514 </Policies>
3515 </RollingFile>
3516 </Appenders>
3517 <Loggers>
3518 <Root level="error">
3519 <AppenderRef ref="RollingFile"/>
3520 </Root>
3521 </Loggers>
3522 </Configuration>]]></pre>
3523 <p>
3524 This second example shows a rollover strategy that will keep up to 20 files before removing them.
3525 </p>
3526 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
3527 <Configuration status="warn" name="MyApp" packages="">
3528 <Appenders>
3529 <RollingFile name="RollingFile" fileName="logs/app.log"
3530 filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
3531 <PatternLayout>
3532 <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
3533 </PatternLayout>
3534 <Policies>
3535 <TimeBasedTriggeringPolicy />
3536 <SizeBasedTriggeringPolicy size="250 MB"/>
3537 </Policies>
3538 <DefaultRolloverStrategy max="20"/>
3539 </RollingFile>
3540 </Appenders>
3541 <Loggers>
3542 <Root level="error">
3543 <AppenderRef ref="RollingFile"/>
3544 </Root>
3545 </Loggers>
3546 </Configuration>]]></pre>
3547 <p>
3548 Below is a sample configuration that uses a RollingFileAppender with both the time and size based
3549 triggering policies, will create up to 7 archives on the same day (1-7) that are stored in a directory
3550 based on the current year and month, and will compress each
3551 archive using gzip and will roll every 6 hours when the hour is divisible by 6:
3552 </p>
3553
3554 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
3555 <Configuration status="warn" name="MyApp" packages="">
3556 <Appenders>
3557 <RollingFile name="RollingFile" fileName="logs/app.log"
3558 filePattern="logs/$${date:yyyy-MM}/app-%d{yyyy-MM-dd-HH}-%i.log.gz">
3559 <PatternLayout>
3560 <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
3561 </PatternLayout>
3562 <Policies>
3563 <TimeBasedTriggeringPolicy interval="6" modulate="true"/>
3564 <SizeBasedTriggeringPolicy size="250 MB"/>
3565 </Policies>
3566 </RollingFile>
3567 </Appenders>
3568 <Loggers>
3569 <Root level="error">
3570 <AppenderRef ref="RollingFile"/>
3571 </Root>
3572 </Loggers>
3573 </Configuration>]]></pre>
3574 <p>
3575 This sample configuration uses a RollingFileAppender with both the cron and size based
3576 triggering policies, and writes directly to an unlimited number of archive files. The cron
3577 trigger causes a rollover every hour while the file size is limited to 250MB:
3578 </p>
3579
3580 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
3581 <Configuration status="warn" name="MyApp" packages="">
3582 <Appenders>
3583 <RollingFile name="RollingFile" filePattern="logs/app-%d{yyyy-MM-dd-HH}-%i.log.gz">
3584 <PatternLayout>
3585 <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
3586 </PatternLayout>
3587 <Policies>
3588 <CronTriggeringPolicy schedule="0 0 * * * ?"/>
3589 <SizeBasedTriggeringPolicy size="250 MB"/>
3590 </Policies>
3591 </RollingFile>
3592 </Appenders>
3593 <Loggers>
3594 <Root level="error">
3595 <AppenderRef ref="RollingFile"/>
3596 </Root>
3597 </Loggers>
3598 </Configuration>]]></pre>
3599 <p>
3600 This sample configuration is the same as the previous but limits the number of files saved each hour to 10:
3601 </p>
3602
3603 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
3604 <Configuration status="warn" name="MyApp" packages="">
3605 <Appenders>
3606 <RollingFile name="RollingFile" filePattern="logs/app-%d{yyyy-MM-dd-HH}-%i.log.gz">
3607 <PatternLayout>
3608 <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
3609 </PatternLayout>
3610 <Policies>
3611 <CronTriggeringPolicy schedule="0 0 * * * ?"/>
3612 <SizeBasedTriggeringPolicy size="250 MB"/>
3613 </Policies>
3614 <DirectWriteRolloverStrategy maxFiles="10"/>
3615 </RollingFile>
3616 </Appenders>
3617 <Loggers>
3618 <Root level="error">
3619 <AppenderRef ref="RollingFile"/>
3620 </Root>
3621 </Loggers>
3622 </Configuration>]]></pre>
3623 <a name="CustomDeleteOnRollover"/>
3624 <h5>Log Archive Retention Policy: Delete on Rollover</h5>
3625 <p>
3626 Log4j-2.5 introduces a <tt>Delete</tt> action that gives users more control
3627 over what files are deleted at rollover time than what was possible with the DefaultRolloverStrategy
3628 <tt>max</tt> attribute.
3629 The Delete action lets users configure one or more conditions that select the files to delete
3630 relative to a base directory.
3631 </p>
3632 <p>
3633 Note that it is possible to delete any file, not just rolled over log files, so use this action with care!
3634 With the <tt>testMode</tt> parameter you can test your configuration without accidentally deleting the wrong files.
3635 </p>
3636 <table>
3637 <caption align="top">Delete Parameters</caption>
3638 <tr>
3639 <th>Parameter Name</th>
3640 <th>Type</th>
3641 <th>Description</th>
3642 </tr>
3643 <tr>
3644 <td>basePath</td>
3645 <td>String</td>
3646 <td><em>Required.</em> Base path from where to start scanning for files to delete.</td>
3647 </tr>
3648 <tr>
3649 <td>maxDepth</td>
3650 <td>int</td>
3651 <td>The maximum number of levels of directories to visit. A value of 0
3652 means that only the starting file (the base path itself) is visited,
3653 unless denied by the security manager. A value of
3654 Integer.MAX_VALUE indicates that all levels should be visited. The default is 1,
3655 meaning only the files in the specified base directory.</td>
3656 </tr>
3657 <tr>
3658 <td>followLinks</td>
3659 <td>boolean</td>
3660 <td>Whether to follow symbolic links. Default is false.</td>
3661 </tr>
3662 <tr>
3663 <td>testMode</td>
3664 <td>boolean</td>
3665 <td>If true, files are not deleted but instead a message is printed to the <a
3666 href="configuration.html#StatusMessages">status logger</a> at INFO level.
3667 Use this to do a dry run to test if the configuration works as expected. Default is false.</td>
3668 </tr>
3669 <tr>
3670 <td>pathSorter</td>
3671 <td>PathSorter</td>
3672 <td>A plugin implementing the
3673 <a href="../log4j-core/apidocs/org/apache/logging/log4j/core/appender/rolling/action/PathSorter.html">PathSorter</a>
3674 interface to sort the files before selecting the files to delete. The default is to sort most recently
3675 modified files first.</td>
3676 </tr>
3677 <tr>
3678 <td>pathConditions <a name="DeletePathCondition"/></td>
3679 <td>PathCondition[]</td>
3680 <td><p><em>Required if no ScriptCondition is specified.</em> One or more PathCondition elements.</p>
3681 <p>
3682 If more than one condition is specified,
3683 they all need to accept a path before it is deleted. Conditions can be nested, in which case the
3684 inner condition(s) are evaluated only if the outer condition accepts the path.
3685 If conditions are not nested they may be evaluated in any order.
3686 </p>
3687 <p>
3688 Conditions can also be combined with the logical operators AND, OR and NOT by using the
3689 <tt>IfAll</tt>, <tt>IfAny</tt> and <tt>IfNot</tt> composite conditions.
3690 </p>
3691 <p>Users can create custom conditions or use the built-in conditions:</p>
3692 <ul>
3693 <li><a href="#DeleteIfFileName">IfFileName</a> - accepts files whose path (relative to the base path) matches a
3694 <a href="https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html">regular expression</a> or a
3695 <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystem.html#getPathMatcher(java.lang.String)">glob</a>.</li>
3696 <li><a href="#DeleteIfLastModified">IfLastModified</a> - accepts files that are as old as or older than the specified
3697 <a href="../log4j-core/apidocs/org/apache/logging/log4j/core/appender/rolling/action/Duration.html#parse(CharSequence)">duration</a>.
3698 </li>
3699 <li><a href="#DeleteIfAccumulatedFileCount">IfAccumulatedFileCount</a> - accepts paths after some count threshold is exceeded during the file tree walk.</li>
3700 <li><a href="#DeleteIfAccumulatedFileSize">IfAccumulatedFileSize</a> - accepts paths after the accumulated file size threshold is exceeded during the file tree walk.</li>
3701 <li>IfAll - accepts a path if all nested conditions accept it (logical AND).
3702 Nested conditions may be evaluated in any order.</li>
3703 <li>IfAny - accepts a path if one of the nested conditions accept it (logical OR).
3704 Nested conditions may be evaluated in any order.</li>
3705 <li>IfNot - accepts a path if the nested condition does not accept it (logical NOT).</li>
3706 </ul>
3707 </td>
3708 </tr>
3709 <tr>
3710 <td>scriptCondition <a name="DeleteScriptCondition"/></td>
3711 <td>ScriptCondition</td>
3712 <td><p><em>Required if no PathConditions are specified.</em> A ScriptCondition element specifying a script.</p>
3713 <p>
3714 The ScriptCondition should contain a <a href="#ScriptCondition">Script,
3715 ScriptRef or ScriptFile</a> element that specifies the logic to be executed.
3716 (See also the <a href="filters.html#Script">ScriptFilter</a> documentation for more examples of
3717 configuring ScriptFiles and ScriptRefs.)
3718 </p>
3719 <p>The script is passed a number of <a href="#ScriptParameters">parameters</a>,
3720 including a list of paths found under the base path (up to <tt>maxDepth</tt>)
3721 and must return a list with the paths to delete.</p>
3722 </td>
3723 </tr>
3724 </table>
3725 <a name="DeleteIfFileName"/>
3726 <table>
3727 <caption align="top">IfFileName Condition Parameters</caption>
3728 <tr>
3729 <th>Parameter Name</th>
3730 <th>Type</th>
3731 <th>Description</th>
3732 </tr>
3733 <tr>
3734 <td>glob</td>
3735 <td>String</td>
3736 <td><em>Required if regex not specified.</em>
3737 Matches the relative path (relative to the base path) using a limited pattern language that resembles regular expressions but with a
3738 <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystem.html#getPathMatcher(java.lang.String)">simpler syntax</a>.
3739 </td>
3740 </tr>
3741 <tr>
3742 <td>regex</td>
3743 <td>String</td>
3744 <td><em>Required if glob not specified.</em>
3745 Matches the relative path (relative to the base path) using a regular expression as defined by the
3746 <a href="https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html">Pattern</a> class.
3747 </td>
3748 </tr>
3749 <tr>
3750 <td>nestedConditions</td>
3751 <td>PathCondition[]</td>
3752 <td>An optional set of nested <a href="#DeletePathCondition">PathConditions</a>. If any nested conditions
3753 exist they all need to accept the file before it is deleted. Nested conditions are only evaluated if the
3754 outer condition accepts a file (if the path name matches).
3755 </td>
3756 </tr>
3757 </table>
3758 <a name="DeleteIfLastModified"/>
3759 <table>
3760 <caption align="top">IfLastModified Condition Parameters</caption>
3761 <tr>
3762 <th>Parameter Name</th>
3763 <th>Type</th>
3764 <th>Description</th>
3765 </tr>
3766 <tr>
3767 <td>age</td>
3768 <td>String</td>
3769 <td><em>Required.</em>
3770 Specifies a <a href="../log4j-core/apidocs/org/apache/logging/log4j/core/appender/rolling/action/Duration.html#parse(CharSequence)">duration</a>.
3771 The condition accepts files that are as old or older than the specified duration.
3772 </td>
3773 </tr>
3774 <tr>
3775 <td>nestedConditions</td>
3776 <td>PathCondition[]</td>
3777 <td>An optional set of nested <a href="#DeletePathCondition">PathConditions</a>. If any nested conditions
3778 exist they all need to accept the file before it is deleted. Nested conditions are only evaluated if the
3779 outer condition accepts a file (if the file is old enough).
3780 </td>
3781 </tr>
3782 </table>
3783 <a name="DeleteIfAccumulatedFileCount"/>
3784 <table>
3785 <caption align="top">IfAccumulatedFileCount Condition Parameters</caption>
3786 <tr>
3787 <th>Parameter Name</th>
3788 <th>Type</th>
3789 <th>Description</th>
3790 </tr>
3791 <tr>
3792 <td>exceeds</td>
3793 <td>int</td>
3794 <td><em>Required.</em>
3795 The threshold count from which files will be deleted.
3796 </td>
3797 </tr>
3798 <tr>
3799 <td>nestedConditions</td>
3800 <td>PathCondition[]</td>
3801 <td>An optional set of nested <a href="#DeletePathCondition">PathConditions</a>. If any nested conditions
3802 exist they all need to accept the file before it is deleted. Nested conditions are only evaluated if the
3803 outer condition accepts a file (if the threshold count has been exceeded).
3804 </td>
3805 </tr>
3806 </table>
3807 <a name="DeleteIfAccumulatedFileSize"/>
3808 <table>
3809 <caption align="top">IfAccumulatedFileSize Condition Parameters</caption>
3810 <tr>
3811 <th>Parameter Name</th>
3812 <th>Type</th>
3813 <th>Description</th>
3814 </tr>
3815 <tr>
3816 <td>exceeds</td>
3817 <td>String</td>
3818 <td><em>Required.</em>
3819 The threshold accumulated file size from which files will be deleted.
3820 The size can be specified in bytes, with the suffix KB, MB or GB, for example <tt>20MB</tt>.
3821 </td>
3822 </tr>
3823 <tr>
3824 <td>nestedConditions</td>
3825 <td>PathCondition[]</td>
3826 <td>An optional set of nested <a href="#DeletePathCondition">PathConditions</a>. If any nested conditions
3827 exist they all need to accept the file before it is deleted. Nested conditions are only evaluated if the
3828 outer condition accepts a file (if the threshold accumulated file size has been exceeded).
3829 </td>
3830 </tr>
3831 </table>
3832 <p>
3833 Below is a sample configuration that uses a RollingFileAppender with the cron
3834 triggering policy configured to trigger every day at midnight.
3835 Archives are stored in a directory based on the current year and month.
3836 All files under the base directory that match the "*/app-*.log.gz" glob and are 60 days old
3837 or older are deleted at rollover time.
3838 </p>
3839
3840 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
3841 <Configuration status="warn" name="MyApp" packages="">
3842 <Properties>
3843 <Property name="baseDir">logs</Property>
3844 </Properties>
3845 <Appenders>
3846 <RollingFile name="RollingFile" fileName="${baseDir}/app.log"
3847 filePattern="${baseDir}/$${date:yyyy-MM}/app-%d{yyyy-MM-dd}.log.gz">
3848 <PatternLayout pattern="%d %p %c{1.} [%t] %m%n" />
3849 <CronTriggeringPolicy schedule="0 0 0 * * ?"/>
3850 <DefaultRolloverStrategy>
3851 <Delete basePath="${baseDir}" maxDepth="2">
3852 <IfFileName glob="*/app-*.log.gz" />
3853 <IfLastModified age="60d" />
3854 </Delete>
3855 </DefaultRolloverStrategy>
3856 </RollingFile>
3857 </Appenders>
3858 <Loggers>
3859 <Root level="error">
3860 <AppenderRef ref="RollingFile"/>
3861 </Root>
3862 </Loggers>
3863 </Configuration>]]></pre>
3864 <p>
3865 Below is a sample configuration that uses a RollingFileAppender with both the time and size based
3866 triggering policies, will create up to 100 archives on the same day (1-100) that are stored in a directory
3867 based on the current year and month, and will compress each
3868 archive using gzip and will roll every hour.
3869
3870 During every rollover, this configuration will delete files that match "*/app-*.log.gz"
3871 and are 30 days old or older,
3872 but keep the most recent 100 GB or the most recent 10 files, whichever comes first.
3873 </p>
3874
3875 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
3876 <Configuration status="warn" name="MyApp" packages="">
3877 <Properties>
3878 <Property name="baseDir">logs</Property>
3879 </Properties>
3880 <Appenders>
3881 <RollingFile name="RollingFile" fileName="${baseDir}/app.log"
3882 filePattern="${baseDir}/$${date:yyyy-MM}/app-%d{yyyy-MM-dd-HH}-%i.log.gz">
3883 <PatternLayout pattern="%d %p %c{1.} [%t] %m%n" />
3884 <Policies>
3885 <TimeBasedTriggeringPolicy />
3886 <SizeBasedTriggeringPolicy size="250 MB"/>
3887 </Policies>
3888 <DefaultRolloverStrategy max="100">
3889 <!--
3890 Nested conditions: the inner condition is only evaluated on files
3891 for which the outer conditions are true.
3892 -->
3893 <Delete basePath="${baseDir}" maxDepth="2">
3894 <IfFileName glob="*/app-*.log.gz">
3895 <IfLastModified age="30d">
3896 <IfAny>
3897 <IfAccumulatedFileSize exceeds="100 GB" />
3898 <IfAccumulatedFileCount exceeds="10" />
3899 </IfAny>
3900 </IfLastModified>
3901 </IfFileName>
3902 </Delete>
3903 </DefaultRolloverStrategy>
3904 </RollingFile>
3905 </Appenders>
3906 <Loggers>
3907 <Root level="error">
3908 <AppenderRef ref="RollingFile"/>
3909 </Root>
3910 </Loggers>
3911 </Configuration>]]></pre>
3912 <a name="ScriptCondition"/>
3913 <table>
3914 <caption align="top">ScriptCondition Parameters</caption>
3915 <tr>
3916 <th>Parameter Name</th>
3917 <th>Type</th>
3918 <th>Description</th>
3919 </tr>
3920 <tr>
3921 <td>script</td>
3922 <td>Script, ScriptFile or ScriptRef</td>
3923 <td>The Script element that specifies the logic to be executed. The script is passed
3924 a list of paths found under the base path and must return the paths to delete as a
3925 <tt>java.util.List<<a href="../log4j-core/apidocs/org/apache/logging/log4j/core/appender/rolling/action/PathWithAttributes.html">PathWithAttributes</a>></tt>.
3926 See also the <a href="filters.html#Script">ScriptFilter</a> documentation for an example of
3927 how ScriptFiles and ScriptRefs can be configured.
3928 </td>
3929 </tr>
3930 </table>
3931 <a name="ScriptParameters"/>
3932 <table>
3933 <caption align="top">Script Parameters</caption>
3934 <tr>
3935 <th>Parameter Name</th>
3936 <th>Type</th>
3937 <th>Description</th>
3938 </tr>
3939 <tr>
3940 <td>basePath</td>
3941 <td><tt>java.nio.file.Path</tt></td>
3942 <td>The directory from where the Delete action started scanning for
3943 files to delete. Can be used to relativize the paths in the pathList.</td>
3944 </tr>
3945 <tr>
3946 <td>pathList</td>
3947 <td><tt>java.util.List<<a href="../log4j-core/apidocs/org/apache/logging/log4j/core/appender/rolling/action/PathWithAttributes.html">PathWithAttributes</a>></tt></td>
3948 <td>The list of paths found under the base path up to the specified max depth,
3949 sorted most recently modified files first.
3950 The script is free to modify and return this list.</td>
3951 </tr>
3952 <tr>
3953 <td>statusLogger</td>
3954 <td>StatusLogger</td>
3955 <td>The StatusLogger that can be used to log internal events during script execution.</td>
3956 </tr>
3957 <tr>
3958 <td>configuration</td>
3959 <td>Configuration</td>
3960 <td>The Configuration that owns this ScriptCondition.</td>
3961 </tr>
3962 <tr>
3963 <td>substitutor</td>
3964 <td>StrSubstitutor</td>
3965 <td>The StrSubstitutor used to replace lookup variables.</td>
3966 </tr>
3967 <tr>
3968 <td>?</td>
3969 <td>String</td>
3970 <td>Any properties declared in the configuration.</td>
3971 </tr>
3972 </table>
3973 <p>
3974 Below is a sample configuration that uses a RollingFileAppender with the cron
3975 triggering policy configured to trigger every day at midnight.
3976 Archives are stored in a directory based on the current year and month.
3977 The script returns a list of rolled over files under the base directory dated Friday the 13th.
3978 The Delete action will delete all files returned by the script.
3979 </p>
3980
3981 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
3982 <Configuration status="trace" name="MyApp" packages="">
3983 <Properties>
3984 <Property name="baseDir">logs</Property>
3985 </Properties>
3986 <Appenders>
3987 <RollingFile name="RollingFile" fileName="${baseDir}/app.log"
3988 filePattern="${baseDir}/$${date:yyyy-MM}/app-%d{yyyyMMdd}.log.gz">
3989 <PatternLayout pattern="%d %p %c{1.} [%t] %m%n" />
3990 <CronTriggeringPolicy schedule="0 0 0 * * ?"/>
3991 <DefaultRolloverStrategy>
3992 <Delete basePath="${baseDir}" maxDepth="2">
3993 <ScriptCondition>
3994 <Script name="superstitious" language="groovy"><![CDATA[
3995 import java.nio.file.*;
3996
3997 def result = [];
3998 def pattern = ~/\d*\/app-(\d*)\.log\.gz/;
3999
4000 pathList.each { pathWithAttributes ->
4001 def relative = basePath.relativize pathWithAttributes.path
4002 statusLogger.trace 'SCRIPT: relative path=' + relative + " (base=$basePath)";
4003
4004 // remove files dated Friday the 13th
4005
4006 def matcher = pattern.matcher(relative.toString());
4007 if (matcher.find()) {
4008 def dateString = matcher.group(1);
4009 def calendar = Date.parse("yyyyMMdd", dateString).toCalendar();
4010 def friday13th = calendar.get(Calendar.DAY_OF_MONTH) == 13 \
4011 && calendar.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY;
4012 if (friday13th) {
4013 result.add pathWithAttributes;
4014 statusLogger.trace 'SCRIPT: deleting path ' + pathWithAttributes;
4015 }
4016 }
4017 }
4018 statusLogger.trace 'SCRIPT: returning ' + result;
4019 result;
4020 ]] >
4021 </Script>
4022 </ScriptCondition>
4023 </Delete>
4024 </DefaultRolloverStrategy>
4025 </RollingFile>
4026 </Appenders>
4027 <Loggers>
4028 <Root level="error">
4029 <AppenderRef ref="RollingFile"/>
4030 </Root>
4031 </Loggers>
4032 </Configuration>]]></pre>
4033
4034 <a name="CustomPosixViewAttributeOnRollover"/>
4035 <h5>Log Archive File Attribute View Policy: Custom file attribute on Rollover</h5>
4036 <p>
4037 Log4j-2.9 introduces a <tt>PosixViewAttribute</tt> action that gives users more control
4038 over which file attribute permissions, owner and group should be applied.
4039 The PosixViewAttribute action lets users configure one or more conditions that select the eligible files
4040 relative to a base directory.
4041 </p>
4042 <table>
4043 <caption align="top">PosixViewAttribute Parameters</caption>
4044 <tr>
4045 <th>Parameter Name</th>
4046 <th>Type</th>
4047 <th>Description</th>
4048 </tr>
4049 <tr>
4050 <td>basePath</td>
4051 <td>String</td>
4052 <td><em>Required.</em> Base path from where to start scanning for files to apply attributes.</td>
4053 </tr>
4054 <tr>
4055 <td>maxDepth</td>
4056 <td>int</td>
4057 <td>The maximum number of levels of directories to visit. A value of 0
4058 means that only the starting file (the base path itself) is visited,
4059 unless denied by the security manager. A value of
4060 Integer.MAX_VALUE indicates that all levels should be visited. The default is 1,
4061 meaning only the files in the specified base directory.</td>
4062 </tr>
4063 <tr>
4064 <td>followLinks</td>
4065 <td>boolean</td>
4066 <td>Whether to follow symbolic links. Default is false.</td>
4067 </tr>
4068 <tr>
4069 <td>pathConditions</td>
4070 <td>PathCondition[]</td>
4071 <td>see <a href="#DeletePathCondition">DeletePathCondition</a></td>
4072 </tr>
4073 <tr>
4074 <td>filePermissions</td>
4075 <td>String</td>
4076 <td><p>File attribute permissions in POSIX format to apply when action is executed.</p>
4077 <p>Underlying files system shall support <a class="javadoc" href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/PosixFileAttributeView.html">POSIX</a> file attribute view.</p>
4078 <p>Examples: rw------- or rw-rw-rw- etc...</p></td>
4079 </tr>
4080 <tr>
4081 <td>fileOwner</td>
4082 <td>String</td>
4083 <td><p>File owner to define when action is executed.</p>
4084 <p>Changing file's owner may be restricted for security reason and Operation not permitted IOException thrown.
4085 Only processes with an effective user ID equal to the user ID
4086 of the file or with appropriate privileges may change the ownership of a file
4087 if <a href="http://www.gnu.org/software/libc/manual/html_node/Options-for-Files.html">_POSIX_CHOWN_RESTRICTED</a> is in effect for path.</p>
4088 <p>Underlying files system shall support file <a class="javadoc" href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/FileOwnerAttributeView.html">owner</a> attribute view.</p>
4089 </td>
4090 </tr>
4091 <tr>
4092 <td>fileGroup</td>
4093 <td>String</td>
4094 <td><p>File group to define whene action is executed.</p>
4095 <p>Underlying files system shall support <a class="javadoc" href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/PosixFileAttributeView.html">POSIX</a> file attribute view.</p>
4096 </td>
4097 </tr>
4098 </table>
4099
4100 <p>
4101 Below is a sample configuration that uses a RollingFileAppender and defines different POSIX file attribute view for current and rolled log files.
4102 </p>
4103
4104 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
4105 <Configuration status="trace" name="MyApp" packages="">
4106 <Properties>
4107 <Property name="baseDir">logs</Property>
4108 </Properties>
4109 <Appenders>
4110 <RollingFile name="RollingFile" fileName="${baseDir}/app.log"
4111 filePattern="${baseDir}/$${date:yyyy-MM}/app-%d{yyyyMMdd}.log.gz"
4112 filePermissions="rw-------">
4113 <PatternLayout pattern="%d %p %c{1.} [%t] %m%n" />
4114 <CronTriggeringPolicy schedule="0 0 0 * * ?"/>
4115 <DefaultRolloverStrategy stopCustomActionsOnError="true">
4116 <PosixViewAttribute basePath="${baseDir}/$${date:yyyy-MM}" filePermissions="r--r--r--">
4117 <IfFileName glob="*.gz" />
4118 </PosixViewAttribute>
4119 </DefaultRolloverStrategy>
4120 </RollingFile>
4121 </Appenders>
4122
4123 <Loggers>
4124 <Root level="error">
4125 <AppenderRef ref="RollingFile"/>
4126 </Root>
4127 </Loggers>
4128
4129 </Configuration>]]></pre>
4130 </subsection>
4131
4132 <a name="RollingRandomAccessFileAppender" />
4133 <subsection name="RollingRandomAccessFileAppender">
4134 <p>
4135 The RollingRandomAccessFileAppender is similar to the standard
4136 <a href="#RollingFileAppender">RollingFileAppender</a>
4137 except it is always buffered (this cannot be switched off) and
4138 internally it uses a <tt>ByteBuffer + RandomAccessFile</tt>
4139 instead of a <tt>BufferedOutputStream</tt>.
4140 We saw a 20-200% performance improvement compared to
4141 RollingFileAppender with "bufferedIO=true"
4142 in our <a href="../performance.html#whichAppender">measurements</a>.
4143
4144 The RollingRandomAccessFileAppender writes to the File named in the
4145 fileName parameter and rolls the file over according the
4146 TriggeringPolicy and the RolloverPolicy.
4147
4148 Similar to the RollingFileAppender, RollingRandomAccessFileAppender uses a RollingRandomAccessFileManager
4149 to actually perform the file I/O and perform the rollover. While RollingRandomAccessFileAppender
4150 from different Configurations cannot be shared, the RollingRandomAccessFileManagers can be
4151 if the Manager is accessible. For example, two web applications in a servlet
4152 container can have their own configuration and safely write to the
4153 same file if Log4j is in a ClassLoader that is common to both of them.
4154 </p>
4155 <p>
4156 A RollingRandomAccessFileAppender requires a
4157 <a href="#TriggeringPolicies">TriggeringPolicy</a> and a
4158 <a href="#RolloverStrategies">RolloverStrategy</a>.
4159 The triggering policy determines if a rollover should be performed
4160 while the RolloverStrategy defines how the rollover should be done.
4161 If no RolloverStrategy is configured, RollingRandomAccessFileAppender will use the
4162 <a href="#DefaultRolloverStrategy">DefaultRolloverStrategy</a>.
4163 Since log4j-2.5, a <a href="#CustomDeleteOnRollover">custom delete action</a> can be configured in the
4164 DefaultRolloverStrategy to run at rollover.
4165 </p>
4166 <p>
4167 File locking is not supported by the RollingRandomAccessFileAppender.
4168 </p>
4169 <table>
4170 <caption align="top">RollingRandomAccessFileAppender Parameters</caption>
4171 <tr>
4172 <th>Parameter Name</th>
4173 <th>Type</th>
4174 <th>Description</th>
4175 </tr>
4176 <tr>
4177 <td>append</td>
4178 <td>boolean</td>
4179 <td>When true - the default, records will be appended to the end
4180 of the file. When set to false,
4181 the file will be cleared before
4182 new records are written.
4183 </td>
4184 </tr>
4185 <tr>
4186 <td>filter</td>
4187 <td>Filter</td>
4188 <td>A Filter to determine if the event should be handled by this
4189 Appender. More than one Filter
4190 may be used by using a
4191 CompositeFilter.
4192 </td>
4193 </tr>
4194 <tr>
4195 <td>fileName</td>
4196 <td>String</td>
4197 <td>The name of the file to write to. If the file, or any of its
4198 parent directories, do not exist,
4199 they will be created.
4200 </td>
4201 </tr>
4202 <tr>
4203 <td>filePattern</td>
4204 <td>String</td>
4205 <td>
4206 The pattern of the file name of the archived log file. The format
4207 of the pattern should is dependent on the RolloverStrategu that is used. The DefaultRolloverStrategy
4208 will accept both a date/time pattern compatible with
4209 <a
4210 href="http://download.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html">
4211 SimpleDateFormat</a>
4212 and/or a %i which represents an integer counter. The integer counter
4213 allows specifying a padding, like %3i for space-padding the counter to
4214 3 digits or (usually more useful) %03i for zero-padding the counter to
4215 3 digits. The pattern also supports interpolation at runtime so any of the Lookups (such as the
4216 <a href="./lookups.html#DateLookup">DateLookup</a>
4217 can be included in the pattern.
4218 </td>
4219 </tr>
4220 <tr>
4221 <td>immediateFlush</td>
4222 <td>boolean</td>
4223 <td><p>When set to true - the default, each write will be followed by a flush.
4224 This will guarantee the data is written
4225 to disk but could impact performance.</p>
4226 <p>Flushing after every write is only useful when using this
4227 appender with synchronous loggers. Asynchronous loggers and
4228 appenders will automatically flush at the end of a batch of events,
4229 even if immediateFlush is set to false. This also guarantees
4230 the data is written to disk but is more efficient.</p>
4231 </td>
4232 </tr>
4233 <tr>
4234 <td>bufferSize</td>
4235 <td>int</td>
4236 <td>The buffer size, defaults to 262,144 bytes (256 * 1024).</td>
4237 </tr>
4238 <tr>
4239 <td>layout</td>
4240 <td>Layout</td>
4241 <td>The Layout to use to format the LogEvent. If no layout is supplied the default pattern layout
4242 of "%m%n" will be used.</td>
4243 </tr>
4244
4245 <tr>
4246 <td>name</td>
4247 <td>String</td>
4248 <td>The name of the Appender.</td>
4249 </tr>
4250 <tr>
4251 <td>policy</td>
4252 <td>TriggeringPolicy</td>
4253 <td>The policy to use to determine if a rollover should occur.
4254 </td>
4255 </tr>
4256 <tr>
4257 <td>strategy</td>
4258 <td>RolloverStrategy</td>
4259 <td>The strategy to use to determine the name and location of the
4260 archive file.
4261 </td>
4262 </tr>
4263 <tr>
4264 <td>ignoreExceptions</td>
4265 <td>boolean</td>
4266 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
4267 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
4268 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
4269 <a href="#FailoverAppender">FailoverAppender</a>.</td>
4270 </tr>
4271 <tr>
4272 <td>filePermissions</td>
4273 <td>String</td>
4274 <td><p>File attribute permissions in POSIX format to apply whenever the file is created.</p>
4275 <p>Underlying files system shall support <a class="javadoc" href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/PosixFileAttributeView.html">POSIX</a> file attribute view.</p>
4276 <p>Examples: <code>rw-------</code> or <code>rw-rw-rw-</code> etc...</p></td>
4277 </tr>
4278 <tr>
4279 <td>fileOwner</td>
4280 <td>String</td>
4281 <td><p>File owner to define whenever the file is created.</p>
4282 <p>Changing file's owner may be restricted for security reason and Operation not permitted IOException thrown.
4283 Only processes with an effective user ID equal to the user ID
4284 of the file or with appropriate privileges may change the ownership of a file
4285 if <a href="http://www.gnu.org/software/libc/manual/html_node/Options-for-Files.html">_POSIX_CHOWN_RESTRICTED</a> is in effect for path.</p>
4286 <p>Underlying files system shall support file <a class="javadoc" href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/FileOwnerAttributeView.html">owner</a> attribute view.</p>
4287 </td>
4288 </tr>
4289 <tr>
4290 <td>fileGroup</td>
4291 <td>String</td>
4292 <td><p>File group to define whenever the file is created.</p>
4293 <p>Underlying files system shall support <a class="javadoc" href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/PosixFileAttributeView.html">POSIX</a> file attribute view.</p>
4294 </td>
4295 </tr>
4296 </table>
4297 <a name="FRFA_TriggeringPolicies" />
4298 <h4>Triggering Policies</h4>
4299 <p>
4300 See
4301 <a href="#TriggeringPolicies">RollingFileAppender Triggering Policies</a>.
4302 </p>
4303 <a name="FRFA_RolloverStrategies" />
4304 <h4>Rollover Strategies</h4>
4305 <p>
4306 See
4307 <a href="#RolloverStrategies">RollingFileAppender Rollover Strategies</a>.
4308 </p>
4309
4310 <p>
4311 Below is a sample configuration that uses a RollingRandomAccessFileAppender
4312 with both the time and size based
4313 triggering policies, will create
4314 up to 7 archives on the same day (1-7) that
4315 are stored in a
4316 directory
4317 based on the current year and month, and will compress
4318 each
4319 archive using gzip:
4320 </p>
4321
4322 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
4323 <Configuration status="warn" name="MyApp" packages="">
4324 <Appenders>
4325 <RollingRandomAccessFile name="RollingRandomAccessFile" fileName="logs/app.log"
4326 filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
4327 <PatternLayout>
4328 <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
4329 </PatternLayout>
4330 <Policies>
4331 <TimeBasedTriggeringPolicy />
4332 <SizeBasedTriggeringPolicy size="250 MB"/>
4333 </Policies>
4334 </RollingRandomAccessFile>
4335 </Appenders>
4336 <Loggers>
4337 <Root level="error">
4338 <AppenderRef ref="RollingRandomAccessFile"/>
4339 </Root>
4340 </Loggers>
4341 </Configuration>]]></pre>
4342 <p>
4343 This second example shows a rollover strategy that will keep up to
4344 20 files before removing them.
4345 </p>
4346 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
4347 <Configuration status="warn" name="MyApp" packages="">
4348 <Appenders>
4349 <RollingRandomAccessFile name="RollingRandomAccessFile" fileName="logs/app.log"
4350 filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
4351 <PatternLayout>
4352 <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
4353 </PatternLayout>
4354 <Policies>
4355 <TimeBasedTriggeringPolicy />
4356 <SizeBasedTriggeringPolicy size="250 MB"/>
4357 </Policies>
4358 <DefaultRolloverStrategy max="20"/>
4359 </RollingRandomAccessFile>
4360 </Appenders>
4361 <Loggers>
4362 <Root level="error">
4363 <AppenderRef ref="RollingRandomAccessFile"/>
4364 </Root>
4365 </Loggers>
4366 </Configuration>]]></pre>
4367 <p>
4368 Below is a sample configuration that uses a RollingRandomAccessFileAppender
4369 with both the time and size based
4370 triggering policies, will create
4371 up to 7 archives on the same day (1-7) that
4372 are stored in a
4373 directory
4374 based on the current year and month, and will compress
4375 each
4376 archive using gzip and will roll every 6 hours when the hour is
4377 divisible
4378 by 6:
4379 </p>
4380
4381 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
4382 <Configuration status="warn" name="MyApp" packages="">
4383 <Appenders>
4384 <RollingRandomAccessFile name="RollingRandomAccessFile" fileName="logs/app.log"
4385 filePattern="logs/$${date:yyyy-MM}/app-%d{yyyy-MM-dd-HH}-%i.log.gz">
4386 <PatternLayout>
4387 <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
4388 </PatternLayout>
4389 <Policies>
4390 <TimeBasedTriggeringPolicy interval="6" modulate="true"/>
4391 <SizeBasedTriggeringPolicy size="250 MB"/>
4392 </Policies>
4393 </RollingRandomAccessFile>
4394 </Appenders>
4395 <Loggers>
4396 <Root level="error">
4397 <AppenderRef ref="RollingRandomAccessFile"/>
4398 </Root>
4399 </Loggers>
4400 </Configuration>]]></pre>
4401 </subsection>
4402 <a name="RoutingAppender"/>
4403 <subsection name="RoutingAppender">
4404 <p>
4405 The RoutingAppender evaluates LogEvents and then routes them to a subordinate Appender. The target
4406 Appender may be an appender previously configured and may be referenced by its name or the
4407 Appender can be dynamically created as needed. The RoutingAppender should be configured after any
4408 Appenders it references to allow it to shut down properly.
4409 </p>
4410 <p>
4411 You can also configure a RoutingAppender with scripts: you can run a script when the appender starts
4412 and when a route is chosen for an log event.
4413 </p>
4414 <table>
4415 <caption align="top">RoutingAppender Parameters</caption>
4416 <tr>
4417 <th>Parameter Name</th>
4418 <th>Type</th>
4419 <th>Description</th>
4420 </tr>
4421 <tr>
4422 <td>Filter</td>
4423 <td>Filter</td>
4424 <td>A Filter to determine if the event should be handled by this Appender. More than one Filter
4425 may be used by using a CompositeFilter.</td>
4426 </tr>
4427 <tr>
4428 <td>name</td>
4429 <td>String</td>
4430 <td>The name of the Appender.</td>
4431 </tr>
4432 <tr>
4433 <td>RewritePolicy</td>
4434 <td>RewritePolicy</td>
4435 <td>The RewritePolicy that will manipulate the LogEvent.</td>
4436 </tr>
4437 <tr>
4438 <td>Routes</td>
4439 <td>Routes</td>
4440 <td>Contains one or more Route declarations to identify the criteria for choosing Appenders.</td>
4441 </tr>
4442 <tr>
4443 <td>Script</td>
4444 <td>Script</td>
4445 <td>
4446 <p>
4447 This Script runs when Log4j starts the RoutingAppender and returns a String Route key to
4448 determine the default Route.
4449 </p>
4450 <p>
4451 This script is passed the following variables:
4452 </p>
4453 <table>
4454 <caption align="top">RoutingAppender Script Parameters</caption>
4455 <tr>
4456 <th>Parameter Name</th>
4457 <th>Type</th>
4458 <th>Description</th>
4459 </tr>
4460 <tr>
4461 <td>configuration</td>
4462 <td>Configuration</td>
4463 <td>The active Configuration.</td>
4464 </tr>
4465 <tr>
4466 <td>staticVariables</td>
4467 <td>Map</td>
4468 <td>
4469 A Map shared between all script invocations for this appender instance. This is
4470 the same map passed to the Routes Script.
4471 </td>
4472 </tr>
4473 </table>
4474 </td>
4475 </tr>
4476 <tr>
4477 <td>ignoreExceptions</td>
4478 <td>boolean</td>
4479 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
4480 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
4481 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
4482 <a href="#FailoverAppender">FailoverAppender</a>.</td>
4483 </tr>
4484 </table>
4485 <p>
4486 In this example, the script causes the "ServiceWindows" route to be the default route on Windows and
4487 "ServiceOther" on all other operating systems. Note that the List Appender is one of our test appenders,
4488 any appender can be used, it is only used as a shorthand.
4489 </p>
4490 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
4491 <Configuration status="WARN" name="RoutingTest">
4492 <Appenders>
4493 <Routing name="Routing">
4494 <Script name="RoutingInit" language="JavaScript"><![CDATA[
4495 importPackage(java.lang);
4496 System.getProperty("os.name").search("Windows") > -1 ? "ServiceWindows" : "ServiceOther";]]]]><![CDATA[>
4497 </Script>
4498 <Routes>
4499 <Route key="ServiceOther">
4500 <List name="List1" />
4501 </Route>
4502 <Route key="ServiceWindows">
4503 <List name="List2" />
4504 </Route>
4505 </Routes>
4506 </Routing>
4507 </Appenders>
4508 <Loggers>
4509 <Root level="error">
4510 <AppenderRef ref="Routing" />
4511 </Root>
4512 </Loggers>
4513 </Configuration>]]></pre>
4514 <h4>Routes</h4>
4515 <p>
4516 The Routes element accepts a single attribute named "pattern". The pattern is evaluated
4517 against all the registered Lookups and the result is used to select a Route. Each Route may be
4518 configured with a key. If the key matches the result of evaluating the pattern then that Route
4519 will be selected. If no key is specified on a Route then that Route is the default. Only one Route
4520 can be configured as the default.
4521 </p>
4522 <p>
4523 The Routes element may contain a Script child element. If specified, the Script is run for each
4524 log event and returns the String Route key to use.
4525 </p>
4526 <p>
4527 You must specify either the pattern attribute or the Script element, but not both.
4528 </p>
4529 <p>
4530 Each Route must reference an Appender. If the Route contains a ref attribute then the
4531 Route will reference an Appender that was defined in the configuration. If the Route contains an
4532 Appender definition then an Appender will be created within the context of the RoutingAppender and
4533 will be reused each time a matching Appender name is referenced through a Route.
4534 </p>
4535 <p>
4536 This script is passed the following variables:
4537 </p>
4538 <table>
4539 <caption align="top">RoutingAppender Routes Script Parameters</caption>
4540 <tr>
4541 <th>Parameter Name</th>
4542 <th>Type</th>
4543 <th>Description</th>
4544 </tr>
4545 <tr>
4546 <td>configuration</td>
4547 <td>Configuration</td>
4548 <td>The active Configuration.</td>
4549 </tr>
4550 <tr>
4551 <td>staticVariables</td>
4552 <td>Map</td>
4553 <td>
4554 A Map shared between all script invocations for this appender instance. This is
4555 the same map passed to the Routes Script.
4556 </td>
4557 </tr>
4558 <tr>
4559 <td>logEvent</td>
4560 <td>LogEvent</td>
4561 <td>The log event.</td>
4562 </tr>
4563 </table>
4564 <p>
4565 In this example, the script runs for each log event and picks a route based on the presence of a
4566 Marker named "AUDIT".
4567 </p>
4568 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
4569 <Configuration status="WARN" name="RoutingTest">
4570 <Appenders>
4571 <Console name="STDOUT" target="SYSTEM_OUT" />
4572 <Flume name="AuditLogger" compress="true">
4573 <Agent host="192.168.10.101" port="8800"/>
4574 <Agent host="192.168.10.102" port="8800"/>
4575 <RFC5424Layout enterpriseNumber="18060" includeMDC="true" appName="MyApp"/>
4576 </Flume>
4577 <Routing name="Routing">
4578 <Routes>
4579 <Script name="RoutingInit" language="JavaScript"><![CDATA[
4580 if (logEvent.getMarker() != null && logEvent.getMarker().isInstanceOf("AUDIT")) {
4581 return "AUDIT";
4582 } else if (logEvent.getContextMap().containsKey("UserId")) {
4583 return logEvent.getContextMap().get("UserId");
4584 }
4585 return "STDOUT";]]]]><![CDATA[>
4586 </Script>
4587 <Route>
4588 <RollingFile
4589 name="Rolling-${mdc:UserId}"
4590 fileName="${mdc:UserId}.log"
4591 filePattern="${mdc:UserId}.%i.log.gz">
4592 <PatternLayout>
4593 <pattern>%d %p %c{1.} [%t] %m%n</pattern>
4594 </PatternLayout>
4595 <SizeBasedTriggeringPolicy size="500" />
4596 </RollingFile>
4597 </Route>
4598 <Route ref="AuditLogger" key="AUDIT"/>
4599 <Route ref="STDOUT" key="STDOUT"/>
4600 </Routes>
4601 <IdlePurgePolicy timeToLive="15" timeUnit="minutes"/>
4602 </Routing>
4603 </Appenders>
4604 <Loggers>
4605 <Root level="error">
4606 <AppenderRef ref="Routing" />
4607 </Root>
4608 </Loggers>
4609 </Configuration>
4610 ]]></pre>
4611 <h4>Purge Policy</h4>
4612 <p>The RoutingAppender can be configured with a PurgePolicy whose purpose is to stop and remove dormant
4613 Appenders that have been dynamically created by the RoutingAppender. Log4j currently provides the
4614 IdlePurgePolicy as the only PurgePolicy available for cleaning up the Appenders. The IdlePurgePolicy
4615 accepts 2 attributes; timeToLive, which is the number of timeUnits the Appender should survive without
4616 having any events sent to it, and timeUnit, the String representation of java.util.concurrent.TimeUnit
4617 which is used with the timeToLive attribute.</p>
4618 <p>
4619 Below is a sample configuration that uses a RoutingAppender to route all Audit events to
4620 a FlumeAppender and all other events will be routed to a RollingFileAppender that captures only
4621 the specific event type. Note that the AuditAppender was predefined while the RollingFileAppenders
4622 are created as needed.
4623 </p>
4624
4625 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
4626 <Configuration status="warn" name="MyApp" packages="">
4627 <Appenders>
4628 <Flume name="AuditLogger" compress="true">
4629 <Agent host="192.168.10.101" port="8800"/>
4630 <Agent host="192.168.10.102" port="8800"/>
4631 <RFC5424Layout enterpriseNumber="18060" includeMDC="true" appName="MyApp"/>
4632 </Flume>
4633 <Routing name="Routing">
4634 <Routes pattern="$${sd:type}">
4635 <Route>
4636 <RollingFile name="Rolling-${sd:type}" fileName="${sd:type}.log"
4637 filePattern="${sd:type}.%i.log.gz">
4638 <PatternLayout>
4639 <pattern>%d %p %c{1.} [%t] %m%n</pattern>
4640 </PatternLayout>
4641 <SizeBasedTriggeringPolicy size="500" />
4642 </RollingFile>
4643 </Route>
4644 <Route ref="AuditLogger" key="Audit"/>
4645 </Routes>
4646 <IdlePurgePolicy timeToLive="15" timeUnit="minutes"/>
4647 </Routing>
4648 </Appenders>
4649 <Loggers>
4650 <Root level="error">
4651 <AppenderRef ref="Routing"/>
4652 </Root>
4653 </Loggers>
4654 </Configuration>]]></pre>
4655 </subsection>
4656 <a name="SMTPAppender"/>
4657 <subsection name="SMTPAppender">
4658 <p>
4659 Sends an e-mail when a specific logging event occurs, typically on errors or fatal errors.
4660 </p>
4661 <p>
4662 The number of logging events delivered in this e-mail depend on the value of
4663 <b>BufferSize</b> option. The <code>SMTPAppender</code> keeps only the last
4664 <code>BufferSize</code> logging events in its cyclic buffer. This keeps
4665 memory requirements at a reasonable level while still delivering useful
4666 application context. All events in the buffer are included in the email.
4667 The buffer will contain the most recent events of level TRACE to WARN
4668 preceding the event that triggered the email.
4669 </p>
4670 <p>
4671 The default behavior is to trigger sending an email whenever an ERROR or higher
4672 severity event is logged and to format it as HTML. The circumstances on when the
4673 email is sent can be controlled by setting one or more filters on the Appender.
4674 As with other Appenders, the formatting can be controlled by specifying a Layout
4675 for the Appender.
4676 </p>
4677 <table>
4678 <caption align="top">SMTPAppender Parameters</caption>
4679 <tr>
4680 <th>Parameter Name</th>
4681 <th>Type</th>
4682 <th>Description</th>
4683 </tr>
4684 <tr>
4685 <td>name</td>
4686 <td>String</td>
4687 <td>The name of the Appender.</td>
4688 </tr>
4689 <tr>
4690 <td>from</td>
4691 <td>String</td>
4692 <td>The email address of the sender.</td>
4693 </tr>
4694 <tr>
4695 <td>replyTo</td>
4696 <td>String</td>
4697 <td>The comma-separated list of reply-to email addresses.</td>
4698 </tr>
4699 <tr>
4700 <td>to</td>
4701 <td>String</td>
4702 <td>The comma-separated list of recipient email addresses.</td>
4703 </tr>
4704 <tr>
4705 <td>cc</td>
4706 <td>String</td>
4707 <td>The comma-separated list of CC email addresses.</td>
4708 </tr>
4709 <tr>
4710 <td>bcc</td>
4711 <td>String</td>
4712 <td>The comma-separated list of BCC email addresses.</td>
4713 </tr>
4714 <tr>
4715 <td>subject</td>
4716 <td>String</td>
4717 <td>The subject of the email message.</td>
4718 </tr>
4719 <tr>
4720 <td>bufferSize</td>
4721 <td>integer</td>
4722 <td>The maximum number of log events to be buffered for inclusion in the message. Defaults to 512.</td>
4723 </tr>
4724 <tr>
4725 <td>layout</td>
4726 <td>Layout</td>
4727 <td>The Layout to use to format the LogEvent. If no layout is supplied <a href="layouts.html#HTMLLayout">HTML layout</a> will be used.</td>
4728 </tr>
4729 <tr>
4730 <td>filter</td>
4731 <td>Filter</td>
4732 <td>A Filter to determine if the event should be handled by this Appender. More than one Filter
4733 may be used by using a CompositeFilter.
4734 </td>
4735 </tr>
4736 <tr>
4737 <td>smtpDebug</td>
4738 <td>boolean</td>
4739 <td>When set to true enables session debugging on STDOUT. Defaults to false.</td>
4740 </tr>
4741 <tr>
4742 <td>smtpHost</td>
4743 <td>String</td>
4744 <td>The SMTP hostname to send to. This parameter is required.</td>
4745 </tr>
4746 <tr>
4747 <td>smtpPassword</td>
4748 <td>String</td>
4749 <td>The password required to authenticate against the SMTP server.</td>
4750 </tr>
4751 <tr>
4752 <td>smtpPort</td>
4753 <td>integer</td>
4754 <td>The SMTP port to send to. </td>
4755 </tr>
4756 <tr>
4757 <td>smtpProtocol</td>
4758 <td>String</td>
4759 <td>The SMTP transport protocol (such as "smtps", defaults to "smtp").</td>
4760 </tr>
4761 <tr>
4762 <td>smtpUsername</td>
4763 <td>String</td>
4764 <td>The username required to authenticate against the SMTP server.</td>
4765 </tr>
4766 <tr>
4767 <td>ignoreExceptions</td>
4768 <td>boolean</td>
4769 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
4770 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
4771 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
4772 <a href="#FailoverAppender">FailoverAppender</a>.</td>
4773 </tr>
4774 </table>
4775 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
4776 <Configuration status="warn" name="MyApp" packages="">
4777 <Appenders>
4778 <SMTP name="Mail" subject="Error Log" to="errors@logging.apache.org" from="test@logging.apache.org"
4779 smtpHost="localhost" smtpPort="25" bufferSize="50">
4780 </SMTP>
4781 </Appenders>
4782 <Loggers>
4783 <Root level="error">
4784 <AppenderRef ref="Mail"/>
4785 </Root>
4786 </Loggers>
4787 </Configuration>]]></pre>
4788 </subsection>
4789 <a name="ScriptAppenderSelector"/>
4790 <subsection name="ScriptAppenderSelector">
4791 <p>
4792 When the configuration is built, the <code>ScriptAppenderSelector</code> appender calls a <code>Script</code>
4793 to compute an appender name. Log4j then creates one of the appender named listed under
4794 <code>AppenderSet</code> using the name of the <code>ScriptAppenderSelector</code>. After configuration, Log4j
4795 ignores the <code>ScriptAppenderSelector</code>. Log4j only builds the one selected appender from the
4796 configuration tree, and ignores other <code>AppenderSet</code> child nodes.
4797 </p>
4798 <p>
4799 In the following example, the script returns the name "List2". The appender name is recorded under
4800 the name of the <code>ScriptAppenderSelector</code>, not the name of the selected appender, in this example,
4801 "SelectIt".
4802 </p>
4803 <pre class="prettyprint linenums"><![CDATA[<Configuration status="WARN" name="ScriptAppenderSelectorExample">
4804 <Appenders>
4805 <ScriptAppenderSelector name="SelectIt">
4806 <Script language="JavaScript"><![CDATA[
4807 importPackage(java.lang);
4808 System.getProperty("os.name").search("Windows") > -1 ? "MyCustomWindowsAppender" : "MySyslogAppender";]]]]><![CDATA[>
4809 </Script>
4810 <AppenderSet>
4811 <MyCustomWindowsAppender name="MyAppender" ... />
4812 <SyslogAppender name="MySyslog" ... />
4813 </AppenderSet>
4814 </ScriptAppenderSelector>
4815 </Appenders>
4816 <Loggers>
4817 <Root level="error">
4818 <AppenderRef ref="SelectIt" />
4819 </Root>
4820 </Loggers>
4821 </Configuration>]]></pre>
4822 </subsection>
4823 <a name="SocketAppender"/>
4824 <subsection name="SocketAppender">
4825 <p>
4826 The <code>SocketAppender</code> is an OutputStreamAppender that writes its output to a remote destination
4827 specified by a host and port. The data can be sent over either TCP or UDP and can be sent in any format.
4828 You can optionally secure communication with <a href="#SSL">SSL</a>. Note that the TCP and SSL variants
4829 write to the socket as a stream and do not expect response from the target destination. Due to limitations
4830 in the TCP protocol that means that when the target server closes its connection some log events may
4831 continue to appear to succeed until a closed connection exception is raised, causing those events to be
4832 lost. If guaranteed delivery is required a protocol that requires acknowledgements must be used.
4833 </p>
4834 <table>
4835 <caption align="top"><code>SocketAppender</code> Parameters</caption>
4836 <tr>
4837 <th>Parameter Name</th>
4838 <th>Type</th>
4839 <th>Description</th>
4840 </tr>
4841 <tr>
4842 <td>name</td>
4843 <td>String</td>
4844 <td>The name of the Appender.</td>
4845 </tr>
4846 <tr>
4847 <td>host</td>
4848 <td>String</td>
4849 <td>The name or address of the system that is listening for log events. This parameter is required. If
4850 the host name resolves to multiple IP addresses the TCP and SSL variations will fail over to
4851 the next IP address when a connection is lost.
4852 </td>
4853 </tr>
4854 <tr>
4855 <td>port</td>
4856 <td>integer</td>
4857 <td>The port on the host that is listening for log events. This parameter must be specified.</td>
4858 </tr>
4859 <tr>
4860 <td>protocol</td>
4861 <td>String</td>
4862 <td>"TCP" (default), "SSL" or "UDP".</td>
4863 </tr>
4864 <tr>
4865 <td>SSL</td>
4866 <td>SslConfiguration</td>
4867 <td>Contains the configuration for the KeyStore and TrustStore. See <a href="#SSL">SSL</a>.</td>
4868 </tr>
4869 <tr>
4870 <td>filter</td>
4871 <td>Filter</td>
4872 <td>A Filter to determine if the event should be handled by this Appender. More than one Filter
4873 may be used by using a CompositeFilter.</td>
4874 </tr>
4875 <tr>
4876 <td>immediateFail</td>
4877 <td>boolean</td>
4878 <td>When set to true, log events will not wait to try to reconnect and will fail immediately if the
4879 socket is not available.</td>
4880 </tr>
4881 <tr>
4882 <td>immediateFlush</td>
4883 <td>boolean</td>
4884 <td>When set to true - the default, each write will be followed by a flush.
4885 This will guarantee the data is written
4886 to disk but could impact performance.</td>
4887 </tr>
4888 <tr>
4889 <td>bufferedIO</td>
4890 <td>boolean</td>
4891 <td>When true - the default, events are written to a buffer and the data will be written to
4892 the socket when the buffer is full or, if immediateFlush is set, when the record is written.</td>
4893 </tr>
4894 <tr>
4895 <td>bufferSize</td>
4896 <td>int</td>
4897 <td>When bufferedIO is true, this is the buffer size, the default is 8192 bytes.</td>
4898 </tr>
4899 <tr>
4900 <td>layout</td>
4901 <td>Layout</td>
4902 <td>The Layout to use to format the LogEvent. Required, there is no default.
4903 <em>New since 2.9, in previous versions SerializedLayout was default.</em></td>
4904 </tr>
4905 <tr>
4906 <td>reconnectionDelayMillis</td>
4907 <td>integer</td>
4908 <td>If set to a value greater than 0, after an error the SocketManager will attempt to reconnect to
4909 the server after waiting the specified number of milliseconds. If the reconnect fails then
4910 an exception will be thrown (which can be caught by the application if <code>ignoreExceptions</code> is
4911 set to <code>false</code>).</td>
4912 </tr>
4913 <tr>
4914 <td>connectTimeoutMillis</td>
4915 <td>integer</td>
4916 <td>The connect timeout in milliseconds. The default is 0 (infinite timeout, like Socket.connect()
4917 methods).</td>
4918 </tr>
4919 <tr>
4920 <td>ignoreExceptions</td>
4921 <td>boolean</td>
4922 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
4923 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
4924 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
4925 <a href="#FailoverAppender">FailoverAppender</a>.</td>
4926 </tr>
4927 </table>
4928
4929 <p>
4930 This is an unsecured TCP configuration:
4931 </p>
4932 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
4933 <Configuration status="warn" name="MyApp" packages="">
4934 <Appenders>
4935 <Socket name="socket" host="localhost" port="9500">
4936 <JsonLayout properties="true"/>
4937 </Socket>
4938 </Appenders>
4939 <Loggers>
4940 <Root level="error">
4941 <AppenderRef ref="socket"/>
4942 </Root>
4943 </Loggers>
4944 </Configuration>]]></pre>
4945
4946 <p>
4947 This is a secured <a href="#SSL">SSL</a> configuration:
4948 </p>
4949 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
4950 <Configuration status="warn" name="MyApp" packages="">
4951 <Appenders>
4952 <Socket name="socket" host="localhost" port="9500">
4953 <JsonLayout properties="true"/>
4954 <SSL>
4955 <KeyStore location="log4j2-keystore.jks" passwordEnvironmentVariable="KEYSTORE_PASSWORD"/>
4956 <TrustStore location="truststore.jks" passwordFile="${sys:user.home}/truststore.pwd"/>
4957 </SSL>
4958 </Socket>
4959 </Appenders>
4960 <Loggers>
4961 <Root level="error">
4962 <AppenderRef ref="socket"/>
4963 </Root>
4964 </Loggers>
4965 </Configuration>]]></pre>
4966
4967 </subsection>
4968 <a name="SSL" />
4969 <subsection name="SSL Configuration">
4970 <p>
4971 Several appenders can be configured to use either a plain network connection or a Secure Socket Layer (SSL)
4972 connection. This section documents the parameters available for SSL configuration.
4973 </p>
4974 <table>
4975 <caption align="top">SSL Configuration Parameters</caption>
4976 <tr>
4977 <th>Parameter Name</th>
4978 <th>Type</th>
4979 <th>Description</th>
4980 </tr>
4981 <tr>
4982 <td>protocol</td>
4983 <td>String</td>
4984 <td><code>SSL</code> if omitted.
4985 See also <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#SSLContext">Standard names</a>.</td>
4986 </tr>
4987 <tr>
4988 <td>KeyStore</td>
4989 <td>KeyStore</td>
4990 <td>Contains your private keys and certificates,
4991 and determines which authentication credentials to send to the remote host.</td>
4992 </tr>
4993 <tr>
4994 <td>TrustStore</td>
4995 <td>TrustStore</td>
4996 <td>Contains the CA certificates of the remote counterparty.
4997 Determines whether the remote authentication credentials
4998 (and thus the connection) should be trusted.</td>
4999 </tr>
5000 </table>
5001
5002 <h4>KeyStore</h4>
5003 <p>
5004 The keystore is meant to contain your private keys and certificates,
5005 and determines which authentication credentials to send to the remote host.
5006 </p>
5007
5008 <table>
5009 <caption align="top">KeyStore Configuration Parameters</caption>
5010 <tr>
5011 <th>Parameter Name</th>
5012 <th>Type</th>
5013 <th>Description</th>
5014 </tr>
5015 <tr>
5016 <td>location</td>
5017 <td>String</td>
5018 <td>Path to the keystore file.</td>
5019 </tr>
5020 <tr>
5021 <td>password</td>
5022 <td>char[]</td>
5023 <td>Plain text password to access the keystore. Cannot be combined with either
5024 <code>passwordEnvironmentVariable</code> or <code>passwordFile</code>.</td>
5025 </tr>
5026 <tr>
5027 <td>passwordEnvironmentVariable</td>
5028 <td>String</td>
5029 <td>Name of an environment variable that holds the password. Cannot be combined with either
5030 <code>password</code> or <code>passwordFile</code>.</td>
5031 </tr>
5032 <tr>
5033 <td>passwordFile</td>
5034 <td>String</td>
5035 <td>Path to a file that holds the password. Cannot be combined with either
5036 <code>password</code> or <code>passwordEnvironmentVariable</code>.</td>
5037 </tr>
5038 <tr>
5039 <td>type</td>
5040 <td>String</td>
5041 <td>Optional KeyStore type, e.g. <code>JKS</code>, <code>PKCS12</code>, <code>PKCS11</code>,
5042 <code>BKS</code>, <code>Windows-MY/Windows-ROOT</code>, <code>KeychainStore</code>, etc.
5043 The default is JKS. See also <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#KeyStore">Standard types</a>.</td>
5044 </tr>
5045 <tr>
5046 <td>keyManagerFactoryAlgorithm</td>
5047 <td>String</td>
5048 <td>Optional KeyManagerFactory algorithm. The default is <code>SunX509</code>.
5049 See also <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#KeyManagerFactory">Standard algorithms</a>.</td>
5050 </tr>
5051 </table>
5052
5053 <h4>TrustStore</h4>
5054 <p>
5055 The trust store is meant to contain the CA certificates you are willing to trust
5056 when a remote party presents its certificate. Determines whether the remote authentication credentials
5057 (and thus the connection) should be trusted.
5058 </p><p>
5059 In some cases, they can be one and the same store,
5060 although it is often better practice to use distinct stores (especially when they are file-based).
5061 </p>
5062
5063 <table>
5064 <caption align="top">TrustStore Configuration Parameters</caption>
5065 <tr>
5066 <th>Parameter Name</th>
5067 <th>Type</th>
5068 <th>Description</th>
5069 </tr>
5070 <tr>
5071 <td>location</td>
5072 <td>String</td>
5073 <td>Path to the keystore file.</td>
5074 </tr>
5075 <tr>
5076 <td>password</td>
5077 <td>char[]</td>
5078 <td>Plain text password to access the keystore. Cannot be combined with either
5079 <code>passwordEnvironmentVariable</code> or <code>passwordFile</code>.</td>
5080 </tr>
5081 <tr>
5082 <td>passwordEnvironmentVariable</td>
5083 <td>String</td>
5084 <td>Name of an environment variable that holds the password. Cannot be combined with either
5085 <code>password</code> or <code>passwordFile</code>.</td>
5086 </tr>
5087 <tr>
5088 <td>passwordFile</td>
5089 <td>String</td>
5090 <td>Path to a file that holds the password. Cannot be combined with either
5091 <code>password</code> or <code>passwordEnvironmentVariable</code>.</td>
5092 </tr>
5093 <tr>
5094 <td>type</td>
5095 <td>String</td>
5096 <td>Optional KeyStore type, e.g. <code>JKS</code>, <code>PKCS12</code>, <code>PKCS11</code>,
5097 <code>BKS</code>, <code>Windows-MY/Windows-ROOT</code>, <code>KeychainStore</code>, etc.
5098 The default is JKS. See also <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#KeyStore">Standard types</a>.</td>
5099 </tr>
5100 <tr>
5101 <td>trustManagerFactoryAlgorithm</td>
5102 <td>String</td>
5103 <td>Optional TrustManagerFactory algorithm. The default is <code>SunX509</code>.
5104 See also <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#TrustManagerFactory">Standard algorithms</a>.</td>
5105 </tr>
5106 </table>
5107
5108 <h4>Example</h4>
5109 <pre class="prettyprint linenums"><![CDATA[
5110 ...
5111 <SSL>
5112 <KeyStore location="log4j2-keystore.jks" passwordEnvironmentVariable="KEYSTORE_PASSWORD"/>
5113 <TrustStore location="truststore.jks" passwordFile="${sys:user.home}/truststore.pwd"/>
5114 </SSL>
5115 ...]]></pre>
5116
5117 </subsection>
5118 <a name="SyslogAppender"/>
5119 <subsection name="SyslogAppender">
5120 <p>
5121 The <code>SyslogAppender</code> is a <code>SocketAppender</code> that writes its output to a remote destination
5122 specified by a host and port in a format that conforms with either the BSD Syslog format or the RFC 5424
5123 format. The data can be sent over either TCP or UDP.
5124 </p>
5125 <table>
5126 <caption align="top"><code>SyslogAppender</code> Parameters</caption>
5127 <tr>
5128 <th>Parameter Name</th>
5129 <th>Type</th>
5130 <th>Description</th>
5131 </tr>
5132 <tr>
5133 <td>advertise</td>
5134 <td>boolean</td>
5135 <td>Indicates whether the appender should be advertised.</td>
5136 </tr>
5137 <tr>
5138 <td>appName</td>
5139 <td>String</td>
5140 <td>The value to use as the APP-NAME in the RFC 5424 syslog record.</td>
5141 </tr>
5142 <tr>
5143 <td>charset</td>
5144 <td>String</td>
5145 <td>The character set to use when converting the syslog String to a byte array. The String must be
5146 a valid <a href="http://download.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html">Charset</a>.
5147 If not specified, the default system Charset will be used.</td>
5148 </tr>
5149 <tr>
5150 <td>connectTimeoutMillis</td>
5151 <td>integer</td>
5152 <td>The connect timeout in milliseconds. The default is 0 (infinite timeout, like Socket.connect()
5153 methods).</td>
5154 </tr>
5155 <tr>
5156 <td>enterpriseNumber</td>
5157 <td>integer</td>
5158 <td>The IANA enterprise number as described in
5159 <a href="http://tools.ietf.org/html/rfc5424#section-7.2.2">RFC 5424</a></td>
5160 </tr>
5161 <tr>
5162 <td>filter</td>
5163 <td>Filter</td>
5164 <td>A Filter to determine if the event should be handled by this Appender. More than one Filter
5165 may be used by using a CompositeFilter.</td>
5166 </tr>
5167 <tr>
5168 <td>facility</td>
5169 <td>String</td>
5170 <td>The facility is used to try to classify the message. The facility option must be set to one of
5171 "KERN", "USER", "MAIL", "DAEMON", "AUTH", "SYSLOG", "LPR", "NEWS", "UUCP", "CRON", "AUTHPRIV",
5172 "FTP", "NTP", "AUDIT", "ALERT", "CLOCK", "LOCAL0", "LOCAL1", "LOCAL2", "LOCAL3", "LOCAL4", "LOCAL5",
5173 "LOCAL6", or "LOCAL7". These values may be specified as upper or lower case characters.</td>
5174 </tr>
5175 <tr>
5176 <td>format</td>
5177 <td>String</td>
5178 <td>If set to "RFC5424" the data will be formatted in accordance with RFC 5424. Otherwise, it will
5179 be formatted as a BSD Syslog record. Note that although BSD Syslog records are required to be
5180 1024 bytes or shorter the SyslogLayout does not truncate them. The RFC5424Layout also does not
5181 truncate records since the receiver must accept records of up to 2048 bytes and may accept records
5182 that are longer.</td>
5183 </tr>
5184 <tr>
5185 <td>host</td>
5186 <td>String</td>
5187 <td>The name or address of the system that is listening for log events. This parameter is required.</td>
5188 </tr>
5189 <tr>
5190 <td>id</td>
5191 <td>String</td>
5192 <td>The default structured data id to use when formatting according to RFC 5424. If the LogEvent contains
5193 a StructuredDataMessage the id from the Message will be used instead of this value.</td>
5194 </tr>
5195 <tr>
5196 <td>ignoreExceptions</td>
5197 <td>boolean</td>
5198 <td>The default is <code>true</code>, causing exceptions encountered while appending events to be
5199 internally logged and then ignored. When set to <code>false</code> exceptions will be propagated to the
5200 caller, instead. You must set this to <code>false</code> when wrapping this Appender in a
5201 <a href="#FailoverAppender">FailoverAppender</a>.</td>
5202 </tr>
5203 <tr>
5204 <td>immediateFail</td>
5205 <td>boolean</td>
5206 <td>When set to true, log events will not wait to try to reconnect and will fail immediately if the
5207 socket is not available.</td>
5208 </tr>
5209 <tr>
5210 <td>immediateFlush</td>
5211 <td>boolean</td>
5212 <td>When set to true - the default, each write will be followed by a flush.
5213 This will guarantee the data is written
5214 to disk but could impact performance.</td>
5215 </tr>
5216 <tr>
5217 <td>includeMDC</td>
5218 <td>boolean</td>
5219 <td>Indicates whether data from the ThreadContextMap will be included in the RFC 5424 Syslog record.
5220 Defaults to true.</td>
5221 </tr>
5222 <tr>
5223 <td>Layout</td>
5224 <td>Layout</td>
5225 <td>A custom layout which overrides the <code>format</code> setting.</td>
5226 </tr>
5227 <tr>
5228 <td>loggerFields</td>
5229 <td>List of KeyValuePairs</td>
5230 <td>Allows arbitrary PatternLayout patterns to be included as specified ThreadContext fields; no default
5231 specified. To use, include a >LoggerFields< nested element, containing one or more
5232 >KeyValuePair< elements. Each >KeyValuePair< must have a key attribute, which
5233 specifies the key name which will be used to identify the field within the MDC Structured Data element,
5234 and a value attribute, which specifies the PatternLayout pattern to use as the value.</td>
5235 </tr>
5236 <tr>
5237 <td>mdcExcludes</td>
5238 <td>String</td>
5239 <td>A comma separated list of mdc keys that should be excluded from the LogEvent. This is mutually
5240 exclusive with the mdcIncludes attribute. This attribute only applies to RFC 5424 syslog records.</td>
5241 </tr>
5242 <tr>
5243 <td>mdcIncludes</td>
5244 <td>String</td>
5245 <td>A comma separated list of mdc keys that should be included in the FlumeEvent. Any keys in the MDC
5246 not found in the list will be excluded. This option is mutually exclusive with the mdcExcludes
5247 attribute. This attribute only applies to RFC 5424 syslog records.</td>
5248 </tr>
5249 <tr>
5250 <td>mdcRequired</td>
5251 <td>String</td>
5252 <td>A comma separated list of mdc keys that must be present in the MDC. If a key is not present a
5253 LoggingException will be thrown. This attribute only applies to RFC 5424 syslog records.</td>
5254 </tr>
5255 <tr>
5256 <td>mdcPrefix</td>
5257 <td>String</td>
5258 <td>A string that should be prepended to each MDC key in order to distinguish it from event attributes.
5259 The default string is "mdc:". This attribute only applies to RFC 5424 syslog records.</td>
5260 </tr>
5261 <tr>
5262 <td>messageId</td>
5263 <td>String</td>
5264 <td>The default value to be used in the MSGID field of RFC 5424 syslog records. </td>
5265 </tr>
5266 <tr>
5267 <td>name</td>
5268 <td>String</td>
5269 <td>The name of the Appender.</td>
5270 </tr>
5271 <tr>
5272 <td>newLine</td>
5273 <td>boolean</td>
5274 <td>If true, a newline will be appended to the end of the syslog record. The default is false.</td>
5275 </tr>
5276 <tr>
5277 <td>port</td>
5278 <td>integer</td>
5279 <td>The port on the host that is listening for log events. This parameter must be specified.</td>
5280 </tr>
5281 <tr>
5282 <td>protocol</td>
5283 <td>String</td>
5284 <td>"TCP" or "UDP". This parameter is required.</td>
5285 </tr>
5286 <tr>
5287 <td>SSL</td>
5288 <td>SslConfiguration</td>
5289 <td>Contains the configuration for the KeyStore and TrustStore. See <a href="#SSL">SSL</a>.</td>
5290 </tr>
5291 <tr>
5292 <td>reconnectionDelayMillis</td>
5293 <td>integer</td>
5294 <td>If set to a value greater than 0, after an error the SocketManager will attempt to reconnect to
5295 the server after waiting the specified number of milliseconds. If the reconnect fails then
5296 an exception will be thrown (which can be caught by the application if <code>ignoreExceptions</code> is
5297 set to <code>false</code>).</td>
5298 </tr>
5299 </table>
5300 <p>
5301 A sample syslogAppender configuration that is configured with two <code>SyslogAppender</code>s, one using the BSD
5302 format and one using RFC 5424.
5303 </p>
5304
5305 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
5306 <Configuration status="warn" name="MyApp" packages="">
5307 <Appenders>
5308 <Syslog name="bsd" host="localhost" port="514" protocol="TCP"/>
5309 <Syslog name="RFC5424" format="RFC5424" host="localhost" port="8514"
5310 protocol="TCP" appName="MyApp" includeMDC="true"
5311 facility="LOCAL0" enterpriseNumber="18060" newLine="true"
5312 messageId="Audit" id="App"/>
5313 </Appenders>
5314 <Loggers>
5315 <Logger name="com.mycorp" level="error">
5316 <AppenderRef ref="RFC5424"/>
5317 </Logger>
5318 <Root level="error">
5319 <AppenderRef ref="bsd"/>
5320 </Root>
5321 </Loggers>
5322 </Configuration>]]></pre>
5323
5324 <p>
5325 For <a href="#SSL">SSL</a> this appender writes its output to a remote destination specified by a host and port over SSL in
5326 a format that conforms with either the BSD Syslog format or the RFC 5424 format.
5327 </p>
5328
5329 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
5330 <Configuration status="warn" name="MyApp" packages="">
5331 <Appenders>
5332 <TLSSyslog name="bsd" host="localhost" port="6514">
5333 <SSL>
5334 <KeyStore location="log4j2-keystore.jks" passwordEnvironmentVariable="KEYSTORE_PASSWORD"/>
5335 <TrustStore location="truststore.jks" passwordFile="${sys:user.home}/truststore.pwd"/>
5336 </SSL>
5337 </TLSSyslog>
5338 </Appenders>
5339 <Loggers>
5340 <Root level="error">
5341 <AppenderRef ref="bsd"/>
5342 </Root>
5343 </Loggers>
5344 </Configuration>]]></pre>
5345 </subsection>
5346
5347 <a name="JeroMQAppender"/>
5348 <subsection name="ZeroMQ/JeroMQ Appender">
5349 <p>
5350 The ZeroMQ appender uses the <a href="https://github.com/zeromq/jeromq">JeroMQ</a> library to send log
5351 events to one or more ZeroMQ endpoints.
5352 </p>
5353 <p>
5354 This is a simple JeroMQ configuration:
5355 </p>
5356 <pre class="prettyprint linenums"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
5357 <Configuration name="JeroMQAppenderTest" status="TRACE">
5358 <Appenders>
5359 <JeroMQ name="JeroMQAppender">
5360 <Property name="endpoint">tcp://*:5556</Property>
5361 <Property name="endpoint">ipc://info-topic</Property>
5362 </JeroMQ>
5363 </Appenders>
5364 <Loggers>
5365 <Root level="info">
5366 <AppenderRef ref="JeroMQAppender"/>
5367 </Root>
5368 </Loggers>
5369 </Configuration>]]></pre>
5370 <p>
5371 The table below describes all options. Please consult the JeroMQ and ZeroMQ documentation for details.
5372 </p>
5373 <table>
5374 <caption align="top">JeroMQ Parameters</caption>
5375 <tr>
5376 <th>Parameter Name</th>
5377 <th>Type</th>
5378 <th>Description</th>
5379 </tr>
5380 <tr>
5381 <td>name</td>
5382 <td>String</td>
5383 <td>The name of the Appender. Required.</td>
5384 </tr>
5385 <tr>
5386 <td>Layout</td>
5387 <td>layout</td>
5388 <td>The Layout to use to format the LogEvent. If no layout is supplied the default pattern layout
5389 of "%m%n" will be used.</td>
5390 </tr>
5391 <tr>
5392 <td>Filters</td>
5393 <td>Filter</td>
5394 <td>The Filter(s) of the Appender.</td>
5395 </tr>
5396 <tr>
5397 <td>Properties</td>
5398 <td>Property[]</td>
5399 <td>One or more Property elements, named <code>endpoint</code>.</td>
5400 </tr>
5401 <tr>
5402 <td>ignoreExceptions</td>
5403 <td>boolean</td>
5404 <td>If true, exceptions will be logged and suppressed. If false errors will be logged and then passed to the application.</td>
5405 </tr>
5406 <tr>
5407 <td>affinity</td>
5408 <td>long</td>
5409 <td>The ZMQ_AFFINITY option. Defaults to 0.</td>
5410 </tr>
5411 <tr>
5412 <td>backlog</td>
5413 <td>long</td>
5414 <td>The ZMQ_BACKLOG option. Defaults to 100.</td>
5415 </tr>
5416 <tr>
5417 <td>delayAttachOnConnect</td>
5418 <td>boolean</td>
5419 <td>The ZMQ_DELAY_ATTACH_ON_CONNECT option. Defaults to false.</td>
5420 </tr>
5421 <tr>
5422 <td>identity</td>
5423 <td>byte[]</td>
5424 <td>The ZMQ_IDENTITY option. Defaults to none.</td>
5425 </tr>
5426 <tr>
5427 <td>ipv4Only</td>
5428 <td>boolean</td>
5429 <td>The ZMQ_IPV4ONLY option. Defaults to true.</td>
5430 </tr>
5431 <tr>
5432 <td>linger</td>
5433 <td>long</td>
5434 <td>The ZMQ_LINGER option. Defaults to -1.</td>
5435 </tr>
5436 <tr>
5437 <td>maxMsgSize</td>
5438 <td>long</td>
5439 <td>The ZMQ_MAXMSGSIZE option. Defaults to -1.</td>
5440 </tr>
5441 <tr>
5442 <td>rcvHwm</td>
5443 <td>long</td>
5444 <td>The ZMQ_RCVHWM option. Defaults to 1000.</td>
5445 </tr>
5446 <tr>
5447 <td>receiveBufferSize</td>
5448 <td>long</td>
5449 <td>The ZMQ_RCVBUF option. Defaults to 0.</td>
5450 </tr>
5451 <tr>
5452 <td>receiveTimeOut</td>
5453 <td>int</td>
5454 <td>The ZMQ_RCVTIMEO option. Defaults to -1.</td>
5455 </tr>
5456 <tr>
5457 <td>reconnectIVL</td>
5458 <td>long</td>
5459 <td>The ZMQ_RECONNECT_IVL option. Defaults to 100.</td>
5460 </tr>
5461 <tr>
5462 <td>reconnectIVLMax</td>
5463 <td>long</td>
5464 <td>The ZMQ_RECONNECT_IVL_MAX option. Defaults to 0.</td>
5465 </tr>
5466 <tr>
5467 <td>sendBufferSize</td>
5468 <td>long</td>
5469 <td>The ZMQ_SNDBUF option. Defaults to 0.</td>
5470 </tr>
5471 <tr>
5472 <td>sendTimeOut</td>
5473 <td>int</td>
5474 <td>The ZMQ_SNDTIMEO option. Defaults to -1.</td>
5475 </tr>
5476 <tr>
5477 <td>sndHwm</td>
5478 <td>long</td>
5479 <td>The ZMQ_SNDHWM option. Defaults to 1000.</td>
5480 </tr>
5481 <tr>
5482 <td>tcpKeepAlive</td>
5483 <td>int</td>
5484 <td>The ZMQ_TCP_KEEPALIVE option. Defaults to -1.</td>
5485 </tr>
5486 <tr>
5487 <td>tcpKeepAliveCount</td>
5488 <td>long</td>
5489 <td>The ZMQ_TCP_KEEPALIVE_CNT option. Defaults to -1.</td>
5490 </tr>
5491 <tr>
5492 <td>tcpKeepAliveIdle</td>
5493 <td>long</td>
5494 <td>The ZMQ_TCP_KEEPALIVE_IDLE option. Defaults to -1.</td>
5495 </tr>
5496 <tr>
5497 <td>tcpKeepAliveInterval</td>
5498 <td>long</td>
5499 <td>The ZMQ_TCP_KEEPALIVE_INTVL option. Defaults to -1.</td>
5500 </tr>
5501 <tr>
5502 <td>xpubVerbose</td>
5503 <td>boolean</td>
5504 <td>The ZMQ_XPUB_VERBOSE option. Defaults to false.</td>
5505 </tr>
5506 </table>
5507 </subsection>
5508
5509 </section>
5510 </body>
5511 </document>