<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Chapter 4: Appenders</title> <link rel="stylesheet" type="text/css" href="../css/common.css" /> <link rel="stylesheet" type="text/css" href="../css/screen.css" media="screen" /> <link rel="stylesheet" type="text/css" href="../css/_print.css" media="print" /> <link rel="stylesheet" type="text/css" href="../css/prettify.css" media="screen"/> </head> <body onload="prettyPrint(); decorate();"> <script type="text/javascript">prefix='../';</script> <script type="text/javascript" src="../js/prettify.js"></script> <script type="text/javascript" src="../templates/header.js"></script> <script type="text/javascript" src="../js/dsl.js"></script> <script type="text/javascript" src="../js/jquery-min.js"></script> <script type="text/javascript" src="../js/decorator.js"></script> <div id="left"> <noscript>Please turn on Javascript to view this menu</noscript> <script src="../templates/left.js" type="text/javascript"></script> </div> <div id="right"> <script src="menu.js" type="text/javascript"></script> </div> <div id="content"> <h1>Chapter 4: Appenders</h1> <div class="quote"> <p><em>There is so much to tell about the Western country in that day that it is hard to know where to start. One thing sets off a hundred others. The problem is to decide which one to tell first.</em></p> <p>—JOHN STEINBECK, <em>East of Eden</em></p> </div> <script src="../templates/creative.js" type="text/javascript"></script> <script src="../templates/setup.js" type="text/javascript"></script> <h2><a name="whatIsAnAppender" href="#whatIsAnAppender"><span class="anchor"/></a>What is an Appender?</h2> <p>Logback delegates the task of writing a logging event to components called appenders. Appenders must implement the <a href="../xref/ch/qos/logback/core/Appender.html"><code>ch.qos.logback.core.Appender</code></a> interface. The salient methods of this interface are summarized below: </p> <pre class="prettyprint source">package ch.qos.logback.core; import ch.qos.logback.core.spi.ContextAware; import ch.qos.logback.core.spi.FilterAttachable; import ch.qos.logback.core.spi.LifeCycle; public interface Appender<E> extends LifeCycle, ContextAware, FilterAttachable { public String getName(); public void setName(String name); <b>void doAppend(E event);</b> }</pre> <p>Most of the methods in the <code>Appender</code> interface are setters and getters. A notable exception is the <code>doAppend()</code> method taking an object instance of type <em>E</em> as its only parameter. The actual type of <em>E</em> will vary depending on the logback module. Within the logback-classic module <em>E</em> would be of type <a href="../apidocs/ch/qos/logback/classic/spi/ILoggingEvent.html">ILoggingEvent</a> and within the logback-access module it would be of type <a href="../apidocs/ch/qos/logback/access/spi/AccessEvent.html">AccessEvent</a>. The <code>doAppend()</code> method is perhaps the most important in the logback framework. It is responsible for outputting the logging events in a suitable format to the appropriate output device. </p> <p>Appenders are named entities. This ensures that they can be referenced by name, a quality confirmed to be instrumental in configuration scripts. The <code>Appender</code> interface extends the <code>FilterAttachable</code> interface. It follows that one or more filters can be attached to an appender instance. Filters are discussed in detail in a subsequent chapter. </p> <p>Appenders are ultimately responsible for outputting logging events. However, they may delegate the actual formatting of the event to a <code>Layout</code> or to an <code>Encoder</code> object. Each layout/encoder is associated with one and only one appender, referred to as the owning appender. Some appenders have a built-in or fixed event format. Consequently, they do not require nor have a layout/encoder. For example, the <code>SocketAppender</code> simply serializes logging events before transmitting them over the wire. </p> <h2><a name="AppenderBase" href="#AppenderBase"><span class="anchor"/></a>AppenderBase</h2> <p>The <a href="../xref/ch/qos/logback/core/AppenderBase.html"> <code>ch.qos.logback.core.AppenderBase</code></a> class is an abstract class implementing the <code>Appender</code> interface. It provides basic functionality shared by all appenders, such as methods for getting or setting their name, their activation status, their layout and their filters. It is the super-class of all appenders shipped with logback. Although an abstract class, <code>AppenderBase</code> actually implements the <code>doAppend()</code> method in the <code>Append</code> interface. Perhaps the clearest way to discuss <code>AppenderBase</code> class is by presenting an excerpt of actual source code. </p> <pre class="prettyprint source">public synchronized void doAppend(E eventObject) { // prevent re-entry. if (guard) { return; } try { guard = true; if (!this.started) { if (statusRepeatCount++ < ALLOWED_REPEATS) { addStatus(new WarnStatus( "Attempted to append to non started appender [" + name + "].",this)); } return; } if (getFilterChainDecision(eventObject) == FilterReply.DENY) { return; } // ok, we now invoke the derived class's implementation of append this.append(eventObject); } finally { guard = false; } }</pre> <p>This implementation of the <code>doAppend()</code> method is synchronized. It follows that logging to the same appender from different threads is safe. While a thread, say <em>T</em>, is executing the <code>doAppend()</code> method, subsequent calls by other threads are queued until <em>T</em> leaves the <code>doAppend()</code> method, ensuring <em>T</em>'s exclusive access to the appender. </p> <p>Since such synchronization is not always appropriate, logback ships with <a href="../xref/ch/qos/logback/core/UnsynchronizedAppenderBase.html"><code>ch.qos.logback.core.UnsynchronizedAppenderBase</code></a> which is very similar to the <a href="../xref/ch/qos/logback/core/AppenderBase.html"><code>AppenderBase</code></a> class. For the sake of conciseness, we will be discussing <code>UnsynchronizedAppenderBase</code> in the remainder of this document. </p> <p>The first thing the <code>doAppend()</code> method does is to check whether the guard is set to true. If it is, it immediately exits. If the guard is not set, it is set to true at the next statement. The guard ensures that the <code>doAppend()</code> method will not recursively call itself. Just imagine that a component, called somewhere beyond the <code>append()</code> method, wants to log something. Its call could be directed to the very same appender that just called it resulting in an infinite loop and a stack overflow. </p> <p>In the following statement we check whether the <code>started</code> field is true. If it is not, <code>doAppend()</code> will send a warning message and return. In other words, once an appender is closed, it is impossible to write to it. <code>Appender</code> objects implement the <code>LifeCycle</code> interface, which implies that they implement <code>start()</code>, <code>stop()</code> and <code>isStarted()</code> methods. After setting all the properties of an appender, Joran, logback's configuration framework, calls the <code>start()</code> method to signal the appender to activate its properties. Depending on its kind, an appender may fail to start if certain properties are missing or because of interference between various properties. For example, given that file creation depends on truncation mode, <code>FileAppender</code> cannot act on the value of its <code>File</code> option until the value of the Append option is also known with certainty. The explicit activation step ensures that an appender acts on its properties <em>after</em> their values become known. </p> <p>If the appender could not be started or if it has been stopped, a warning message will be issued through logback's internal status management system. After several attempts, in order to avoid flooding the internal status system with copies of the same warning message, the <code>doAppend()</code> method will stop issuing these warnings. </p> <p>The next <code>if</code> statement checks the result of the attached filters. Depending on the decision resulting from the filter chain, events can be denied or explicitly accepted. In the absence of a decision by the filter chain, events are accepted by default. </p> <p>The <code>doAppend()</code> method then invokes the derived classes' implementation of the <code>append()</code> method. This method does the actual work of appending the event to the appropriate device. </p> <p>Finally, the guard is released so as to allow a subsequent invocation of the <code>doAppend()</code> method. </p> <p>For the remainder of this manual, we reserve the term "option" or alternatively "property" for any attribute that is inferred dynamically using JavaBeans introspection through setter and getter methods. </p> <h1>Logback-core</h1> <p>Logback-core lays the foundation upon which the other logback modules are built. In general, the components in logback-core require some, albeit minimal, customization. However, in the next few sections, we describe several appenders which are ready for use out of the box. </p> <h2><a name="OutputStreamAppender" href="#OutputStreamAppender"><span class="anchor"/></a>OutputStreamAppender </h2> <p><a href="../xref/ch/qos/logback/core/OutputStreamAppender.html"><code>OutputStreamAppender</code></a> appends events to a <code>java.io.OutputStream</code>. This class provides basic services that other appenders build upon. Users do not usually instantiate <code>OutputStreamAppender</code> objects directly, since in general the <code>java.io.OutputStream</code> type cannot be conveniently mapped to a string, as there is no way to specify the target <code>OutputStream</code> object in a configuration script. Simply put, you cannot configure a <code>OutputStreamAppender</code> from a configuration file. However, this does not mean that <code>OutputStreamAppender</code> lacks configurable properties. These properties are described next. </p> <table class="bodyTable striped"> <tr> <th>Property Name</th> <th>Type</th> <th>Description</th> </tr> <tr> <td><span class="prop" name="osaEncoder">encoder</span></td> <td><a href="../xref/ch/qos/logback/core/encoder/Encoder.html"><code>Encoder</code></a></td> <td>Determines the manner in which an event is written to the underlying <code>OutputStreamAppender</code>. Encoders are described in a <a href="encoders.html">dedicated chapter</a>. </td> </tr> </table> <p>The <code>OutputStreamAppender</code> is the super-class of three other appenders, namely <code>ConsoleAppender</code>, <code>FileAppender</code> which in turn is the super class of <code>RollingFileAppender</code>. The next figure illustrates the class diagram for <code>OutputStreamAppender</code> and its subclasses. </p> <img src="images/chapters/appenders/appenderClassDiagram.jpg" alt="A UML diagram showing OutputStreamAppender and sub-classes"/> <h2><a name="ConsoleAppender" href="#ConsoleAppender"><span class="anchor"/></a>ConsoleAppender</h2> <p>The <a href="../xref/ch/qos/logback/core/ConsoleAppender.html"> <code>ConsoleAppender</code></a>, as the name indicates, appends on the console, or more precisely on <em>System.out</em> or <em>System.err</em>, the former being the default target. <code>ConsoleAppender</code> formats events with the help of an encoder specified by the user. Encoders will be discussed in a subsequent chapter. Both <em>System.out</em> and <em>System.err</em> are of type <code>java.io.PrintStream</code>. Consequently, they are wrapped inside an <code>OutputStreamWriter</code> which buffers I/O operations. </p> <table class="bodyTable striped"> <tr> <th>Property Name</th> <th>Type</th> <th>Description</th> </tr> <tr> <td><span class="prop" container="conApp">encoder</span></td> <td> <a href="../xref/ch/qos/logback/core/encoder/Encoder.html"><code>Encoder</code></a> </td> <td>See <code>OutputStreamAppender</code> properties.</td> </tr> <tr> <td><span class="prop" container="conApp">target</span></td> <td><code>String</code></td> <td> One of the String values <em>System.out</em> or <em>System.err</em>. The default target is <em>System.out</em>. </td> </tr> <tr> <td><span class="prop" container="conApp">withJansi</span></td> <td><code>boolean</code></td> <td>By the default <span class="prop">withJansi</span> property is set to <code>false</code>. Setting <span class="prop">withJansi</span> to <code>true</code> activates the <a href="http://jansi.fusesource.org/">Jansi</a> library which provides support for ANSI color codes on Windows machines. On a Windows host, if this property is set to true, then you should put "org.fusesource.jansi:jansi:1.8" on the class path. Note that Unix-based operating systems such as Linux and Mac OS X support ANSI color codes by default. <p>Under the Eclipse IDE, you might want to try the <a href="http://www.mihai-nita.net/eclipse/">ANSI in Eclipse Console</a> plugin. </p> </td> </tr> </table> <p>Here is a sample configuration that uses <code>ConsoleAppender</code>. </p> <p class="example">Example: ConsoleAppender configuration (logback-examples/src/main/java/chapters/appenders/conf/logback-Console.xml)</p> <span class="asGroovy" onclick="return asGroovy('logback_Console');">View as .groovy</span> <pre id="logback_Console" class="prettyprint source"><configuration> <b><appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder by default --> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern> </encoder> </appender></b> <root level="DEBUG"> <appender-ref ref="STDOUT" /> </root> </configuration></pre> <p>After you have set your current path to the <em>logback-examples</em> directory and <a href="../setup.html">set up your class path</a>, you can give the above configuration file a whirl by issuing the following command: </p> <p class="source">java <a href="../xref/chapters/appenders/ConfigurationTester.html">chapters.appenders.ConfigurationTester</a> src/main/java/chapters/appenders/conf/logback-Console.xml</p> <h2><a name="FileAppender" href="#FileAppender"><span class="anchor"/></a>FileAppender</h2> <p>The <a href="../xref/ch/qos/logback/core/FileAppender.html"><code>FileAppender</code></a>, a subclass of <code>OutputStreamAppender</code>, appends log events into a file. The target file is specified by the <span class="prop">File</span> option. If the file already exists, it is either appended to, or truncated depending on the value of the <span class="prop">append</span> property. </p> <table class="bodyTable properties striped"> <tr> <th>Property Name</th> <th>Type</th> <th>Description</th> </tr> <tr> <td><span class="prop" container="fileApppender">append</span></td> <td><code>boolean</code></td> <td>If true, events are appended at the end of an existing file. Otherwise, if <span class="prop">append</span> is false, any existing file is truncated. The <span class="option">append</span> option is set to true by default. </td> </tr> <tr > <td><span class="prop" container="fileApppender">encoder</span></td> <td> <a href="../xref/ch/qos/logback/core/encoder/Encoder.html"><code>Encoder</code></a> </td> <td>See <code>OutputStreamAppender</code> properties.</td> </tr> <tr> <td><span class="prop" container="fileApppender">file</span></td> <td><code>String</code></td> <td>The name of the file to write to. If the file does not exist, it is created. On the MS Windows platform users frequently forget to escape back slashes. For example, the value <em>c:\temp\test.log</em> is not likely to be interpreted properly as <em>'\t'</em> is an escape sequence interpreted as a single tab character <em>(\u0009)</em>. Correct values can be specified as <em>c:/temp/test.log</em> or alternatively as <em>c:\\temp\\test.log</em>. The <span class="prop">File</span> option has no default value. <p>If the parent directory of the file does not exist, <code>FileAppender</code> will automatically create it, including any necessary but nonexistent parent directories. </p> </td> </tr> <tr> <td><span class="prop" name="prudent">prudent</span></td> <td><code>boolean</code></td> <td>In prudent mode, <code>FileAppender</code> will safely write to the specified file, even in the presence of other <code>FileAppender</code> instances running in different JVMs, potentially running on different hosts. The default value for prudent mode is <code>false</code>. <p>Prudent mode can be used in conjunction with <code>RollingFileAppender</code> although some <a href="#prudentWithRolling">restrictions apply</a>.</p> <p>Prudent mode implies that <span class="prop">append</span> property is automatically set to true. </p> <p>Produdent more relies on exclusive file locks. Experiments show that file locks approximately triple (x3) the cost of writing a logging event. On an "average" PC writing to a file located on a <b>local</b> hard disk, when prudent mode is off, it takes about 10 microseconds to write a single logging event. When prudent mode is on, it takes approximately 30 microseconds to output a single logging event. This translates to logging throughput of 100'000 events per second when prudent mode is off and approximately 33'000 events per second in prudent mode. </p> <p>Prudent mode effectively serializes I/O operations between all JVMs writing to the same file. Thus, as the number of JVMs competing to access a file increases so will the delay incurred by each I/O operation. As long as the <em>total</em> number of I/O operations is in the order of 20 log requests per second, the impact on performance should be negligible. Applications generating 100 or more I/O operations per second can see an impact on performance and should avoid using <span class="prop">prudent</span> mode. </p> <p><span class="label">Networked file locks</span> When the log file is located on a networked file system, the cost of prudent mode is even greater. Just as importantly, file locks over a networked file system can be sometimes strongly biased such that the process currently owning the lock immediately re-obtains the lock upon its release. Thus, while one process hogs the lock for the log file, other processes starve waiting for the lock to the point of appearing deadlocked. </p> <p>The impact of prudent mode is highly dependent on network speed as well as the OS implementation details. We provide an very small application called <a href="https://gist.github.com/2794241">FileLockSimulator</a> which can help you simulate the behavior of prudent mode in your environment. </p> </td> </tr> </table> <p><span class="label notice">Immediate Flush</span> By default, each log event is immediately flushed to the underlying output stream. This default approach is safer in the sense that logging events are not lost in case your applicaiton exits without properly closing appenders. However, for significantly increased logging throughput, you may want to set the <span class="prop">immediateFlush</span> property of the underlying <code>Encoder</code> to <code>false</code> . Encoders and in particular <a href="encoders.html#LayoutWrappingEncoder"><code>LayoutWrappingEncoder</code></a> are described in a separate chapter.</p> <p>Below is an example of a configuration file for <code>FileAppender</code>: </p> <p class="example">Example: FileAppender configuration (logback-examples/src/main/java/chapters/appenders/conf/logback-fileAppender.xml)</p> <span class="asGroovy" onclick="return asGroovy('logback-fileAppender');">View as .groovy</span> <pre id="logback-fileAppender" class="prettyprint source"><configuration> <b><appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>testFile.log</file> <append>true</append> <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder by default --> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender></b> <root level="DEBUG"> <appender-ref ref="FILE" /> </root> </configuration></pre> <p>After changing the current directory to <em>logback-examples</em>, run this example by launching the following command: </p> <p class="source">java chapters.appenders.ConfigurationTester src/main/java/chapters/appenders/conf/logback-fileAppender.xml</p> <h3><a name="uniquelyNamed" href="#uniquelyNamed"><span class="anchor"/></a>Uniquely named files (by timestamp)</h3> <p>During the application development phase or in the case of short-lived applications, e.g. batch applications, it is desirable to create a new log file at each new application launch. This is fairly easy to do with the help of the <code><timestamp></code> element. Here's an example.</p> <p class="example">Example: Uniquely named FileAppender configuration by timestamp (logback-examples/src/main/java/chapters/appenders/conf/logback-timestamp.xml)</p> <span class="asGroovy" onclick="return asGroovy('logback-timestamp');">View as .groovy</span> <pre id="logback-timestamp" class="prettyprint source"><configuration> <!-- Insert the current time formatted as "yyyyMMdd'T'HHmmss" under the key "bySecond" into the logger context. This value will be available to all subsequent configuration elements. --> <b><timestamp key="bySecond" datePattern="yyyyMMdd'T'HHmmss"/></b> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <!-- use the previously created timestamp to create a uniquely named log file --> <file><b>log-${bySecond}.txt</b></file> <encoder> <pattern>%logger{35} - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="FILE" /> </root> </configuration></pre> <p>The timestamp element takes two mandatory attributes <span class="attr">key</span> and <span class="attr">datePattern</span> and an optional <span class="attr">timeReference</span> attribute. The <span class="attr">key</span> attribute is the name of the key under which the timestamp will be available to subsequent configuration elements <a href="configuration.html#variableSubstitution">as a variable</a>. The <span class="attr">datePattern</span> attribute denotes the date pattern used to convert the current time (at which the configuration file is parsed) into a string. The date pattern should follow the conventions defined in <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat</a>. The <span class="attr">timeReference</span> attribute denotes the time reference for the time stamp. The default is the interpretation/parsing time of the configuration file, i.e. the current time. However, under certain circumstances it might be useful to use the context birth time as time reference. This can be accomplished by setting the <span class="attr">timeReference</span> attribute to <code>"contextBirth"</code>. </p> <p>Experiment with the <code><timestamp></code> element by running the command:</p> <p class="command">java chapters.appenders.ConfigurationTester src/main/java/chapters/appenders/conf/logback-timestamp.xml</p> <p>To use the logger context birth date as time reference, you would set the <span class="attr">timeReference</span> attribute to "contextBirth" as shown below.</p> <p class="example">Example: Timestamp using context birth date as time reference (logback-examples/src/main/java/chapters/appenders/conf/logback-timestamp-contextBirth.xml)</p> <span class="asGroovy" onclick="return asGroovy('logback-timestamp-contextBirth');">View as .groovy</span> <pre id="logback-timestamp-contextBirth" class="prettyprint source"><configuration> <timestamp key="bySecond" datePattern="yyyyMMdd'T'HHmmss" <b>timeReference="contextBirth"</b>/> ... </configuration></pre> <h2><a name="RollingFileAppender" href="#RollingFileAppender"><span class="anchor"/></a>RollingFileAppender </h2> <p><a href="../xref/ch/qos/logback/core/rolling/RollingFileAppender.html"><code>RollingFileAppender</code></a> extends <code>FileAppender</code> with the capability to rollover log files. For example, <code>RollingFileAppender</code> can log to a file named <em>log.txt</em> file and, once a certain condition is met, change its logging target to another file. </p> <p>There are two important sub-components that interact with <code>RollingFileAppender</code>. The first <code>RollingFileAppender</code> sub-component, namely <code>RollingPolicy</code>, (<a href="#onRollingPolicies">see below</a>) is responsible for undertaking the actions required for a rollover. A second sub-component of <code>RollingFileAppender</code>, namely <code>TriggeringPolicy</code>, (<a href="#TriggeringPolicy">see below</a>) will determine if and exactly when rollover occurs. Thus, <code>RollingPolicy</code> is responsible for the <em>what</em> and <code>TriggeringPolicy</code> is responsible for the <em>when</em>. </p> <p>To be of any use, a <code>RollingFileAppender</code> must have both a <code>RollingPolicy</code> and a <code>TriggeringPolicy</code> set up. However, if its <code>RollingPolicy</code> also implements the <code>TriggeringPolicy</code> interface, then only the former needs to be specified explicitly. </p> <p>Here are the available properties for <code>RollingFileAppender</code>:</p> <table class="bodyTable striped"> <tr> <th>Property Name</th> <th>Type</th> <th>Description</th> </tr> <tr> <td><span class="prop" container="rfa">file</span></td> <td><code>String</code></td> <td>See <code>FileAppender</code> properties.</td> </tr> <tr> <td><span class="prop" container="rfa">append</span></td> <td><code>boolean</code></td> <td>See <code>FileAppender</code> properties.</td> </tr> <tr> <td><span class="prop" container="rfa">encoder</span></td> <td> <a href="../xref/ch/qos/logback/core/encoder/Encoder.html"><code>Encoder</code></a> </td> <td>See <code>OutputStreamAppender</code> properties.</td> </tr> <tr> <td><span class="prop" container="rfa">rollingPolicy</span></td> <td><code>RollingPolicy</code></td> <td>This option is the component that will dictate <code>RollingFileAppender</code>'s behavior when rollover occurs. See more information below. </td> </tr> <tr> <td><span class="prop" container="rfa">triggeringPolicy</span></td> <td><code>TriggeringPolicy</code></td> <td> This option is the component that will tell <code>RollingFileAppender</code> when to activate the rollover procedure. See more information below. </td> </tr> <tr> <td valign="top"><span class="prop" name="prudentWithRolling">prudent</span></td> <td valign="top"><code>boolean</code></td> <td valign="top"> <a href="#FixedWindowRollingPolicy"><code>FixedWindowRollingPolicy</code></a> is not supported in prudent mode. <p> <code>RollingFileAppender</code> supports the prudent mode in conjunction with <a href="#TimeBasedRollingPolicy"><code>TimeBasedRollingPolicy</code></a> albeit with two restrictions. </p> <ol> <li>In prudent mode, file compression is not supported nor allowed. (We can't have one JVM writing to a file while another JVM is compressing it.) </li> <li>The <span class="prop">file</span> property of <code>FileAppender</code> cannot be set and must be left blank. Indeed, most operating systems do not allow renaming of a file while another process has it opened. </li> </ol> See also properties for <code>FileAppender</code>. </td> </tr> </table> <h3><a name="onRollingPolicies" href="#onRollingPolicies"><span class="anchor"/></a>Overview of rolling policies</h3> <p><a href="../xref/ch/qos/logback/core/rolling/RollingPolicy.html"><code>RollingPolicy</code></a> is responsible for the rollover procedure which involves file moving and renaming.</p> <p>The <code>RollingPolicy</code> interface is presented below:</p> <pre class="prettyprint source">package ch.qos.logback.core.rolling; import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.spi.LifeCycle; public interface RollingPolicy extends LifeCycle { <b>public void rollover() throws RolloverFailure;</b> public String getActiveFileName(); public CompressionMode getCompressionMode(); public void setParent(FileAppender appender); }</pre> <p>The <code>rollover</code> method accomplishes the work involved in archiving the current log file. The <code>getActiveFileName()</code> method is called to compute the file name of the current log file (where live logs are written to). As indicated by <code>getCompressionMode</code> method a RollingPolicy is also responsible for determining the compression mode. Lastly, a <code>RollingPolicy</code> is given a reference to its parent via the <code>setParent</code> method. </p> <!-- ================= ================= --> <h4> <a name="TimeBasedRollingPolicy" href="#TimeBasedRollingPolicy"><span class="anchor"/></a>TimeBasedRollingPolicy </h4> <p><a href="../xref/ch/qos/logback/core/rolling/TimeBasedRollingPolicy.html"> <code>TimeBasedRollingPolicy</code></a> is possibly the most popular rolling policy. It defines a rollover policy based on time, for example by day or by month. <code>TimeBasedRollingPolicy</code> assumes the responsibility for rollover as well as for the triggering of said rollover. Indeed, <code>TimeBasedTriggeringPolicy</code> implements <em>both</em> <code>RollingPolicy</code> and <code>TriggeringPolicy</code> interfaces. </p> <p><code>TimeBasedRollingPolicy</code>'s configuration takes one mandatory <span class="prop">fileNamePattern</span> property and several optional properties. </p> <table class="bodyTable striped"> <tr> <th>Property Name</th> <th>Type</th> <th>Description</th> </tr> <tr> <td><span class="prop" container="tbrp">fileNamePattern</span></td> <td><code>String</code></td> <td> The mandatory <span class="prop">fileNamePattern</span> property defines the name of the rolled-over (archived) log files. Its value should consist of the name of the file, plus a suitably placed <em>%d</em> conversion specifier. The <em>%d</em> conversion specifier may contain a date-and-time pattern as specified by the <code>java.text.SimpleDateFormat</code> class. If the date-and-time pattern is omitted, then the default pattern <em>yyyy-MM-dd</em> is assumed. <b>The rollover period is inferred from the value of <span class="prop">fileNamePattern</span>.</b> <p>Note that the <span class="prop">file</span> property in <code>RollingFileAppender</code> (the parent of <code>TimeBasedRollingPolicy</code>) can be either set or omitted. By setting the <span class="prop">file</span> property of the containing <code>FileAppender</code>, you can decouple the location of the active log file and the location of the archived log files. The current logs will be always targeted at the file specified by the <span class="prop">file</span> property. It follows that the name of the currently active log file will not change over time. However, if you choose to omit the <span class="prop">file</span> property, then the active file will be computed anew for each period based on the value of <span class="prop">fileNamePattern</span>. The examples below should clarify this point. </p> <p>The date-and-time pattern, as found within the accolades of %d{} follow java.text.SimpleDateFormat conventions. The forward slash '/' or backward slash '\' characters anywhere within the <span class="option">fileNamePattern</span> property or within the date-and-time pattern will be interpreted as directory separators. </p> <p>It is possible to specify multiple %d tokens but only one of which can be primary, i.e. used to infer the rollover period. All other tokens <em>must</em> be marked as auxiliary by passing the 'aux' parameter (see examples below).</p> </td> </tr> <tr> <td><span class="prop" container="tbrp">maxHistory</span></td> <td>int</td> <td>The optional <span class="prop">maxHistory</span> property controls the maximum number of archive files to keep, deleting older files. For example, if you specify monthly rollover, and set maxHistory to 6, then 6 months worth of archives files will be kept with files older than 6 months deleted. Note as old archived log files are removed, any folders which were created for the purpose of log file archiving will be removed as appropriate. </td> </tr> <tr > <td><span class="prop" container="tbrp">cleanHistoryOnStart</span></td> <td>boolean</td> <td> <p>If set to true, archive removal will be executed on appender start up. By default this property is set to false. </p> <p>Archive removal is normally performed during roll over. However, some applications may not live long enough for roll over to be triggered. It follows that for such short-lived applications archive removal may never get a chance to execute. By setting <span class="prop">cleanHistoryOnStart</span> to true, archive removal is performed at appender start up.</p> </td> </tr> </table> <p>Here are a few <code>fileNamePattern</code> values with an explanation of their effects.</p> <table class="bodyTable striped"> <tr> <th> <span class="prop">fileNamePattern</span> </th> <th>Rollover schedule</th> <th>Example</th> </tr> <tr> <td class="small"> <em>/wombat/foo.%d</em> </td> <td>Daily rollover (at midnight). Due to the omission of the optional time and date pattern for the <em>%d</em> token specifier, the default pattern of <em>yyyy-MM-dd</em> is assumed, which corresponds to daily rollover. </td> <td> <p><span class="prop">file</span> property not set: During November 23rd, 2006, logging output will go to the file <em>/wombat/foo.2006-11-23</em>. At midnight and for the rest of the 24th, logging output will be directed to <em>/wombat/foo.2006-11-24</em>. </p> <p><span class="prop">file</span> property set to <em>/wombat/foo.txt</em>: During November 23rd, 2006, logging output will go to the file <em>/wombat/foo.txt</em>. At midnight, <em>foo.txt</em> will be renamed as <em>/wombat/foo.2006-11-23</em>. A new <em>/wombat/foo.txt</em> file will be created and for the rest of November 24th logging output will be directed to <em>foo.txt</em>. </p> </td> </tr> <tr> <td class="small"> <em>/wombat/%d{yyyy/MM}/foo.txt</em> </td> <td>Rollover at the beginning of each month.</td> <td> <p><span class="prop">file</span> property not set: During the month of October 2006, logging output will go to <em>/wombat/2006/10/foo.txt</em>. After midnight of October 31st and for the rest of November, logging output will be directed to <em>/wombat/2006/11/foo.txt</em>. </p> <p><span class="prop">file</span> property set to <em>/wombat/foo.txt</em>: The active log file will always be <em>/wombat/foo.txt</em>. During the month of October 2006, logging output will go to <em>/wombat/foo.txt</em>. At midnight of October 31st, <em>/wombat/foo.txt</em> will be renamed as <em>/wombat/2006/10/foo.txt</em>. A new <em>/wombat/foo.txt</em> file will be created where logging output will go for the rest of November. At midnight of November 30th, <em>/wombat/foo.txt</em> will be renamed as <em>/wombat/2006/11/foo.txt</em> and so on. </p> </td> </tr> <tr> <td class="small"> <em>/wombat/foo.%d{yyyy-ww}.log</em> </td> <td>Rollover at the first day of each week. Note that the first day of the week depends on the locale.</td> <td>Similar to previous cases, except that rollover will occur at the beginning of every new week. </td> </tr> <tr> <td class="small"> <em>/wombat/foo%d{yyyy-MM-dd_HH}.log</em> </td> <td>Rollover at the top of each hour.</td> <td>Similar to previous cases, except that rollover will occur at the top of every hour. </td> </tr> <tr> <td class="small"> <em>/wombat/foo%d{yyyy-MM-dd_HH-mm}.log</em> </td> <td>Rollover at the beginning of every minute.</td> <td>Similar to previous cases, except that rollover will occur at the beginning of every minute. </td> </tr> <tr> <td class="small"> <em>/foo/%d{yyyy-MM,<b>aux</b>}/%d.log</em> </td> <td>Rollover daily. Archives located under a folder contaning year and month. </td> <td>In this example, the first %d token is marked as <b>aux</b>iliary. The second %d token, with time and date pattern omitted, is then assumed to be primary. Thus, rollover will occur daily (default for %d) and the folder name will depend on the year and month. For example, during the month of November 2006, archived files will all placed under the /foo/2006-11/ folder, e.g <em>/foo/2006-11/2006-11-14.log</em>. </td> </tr> </table> <p>Any forward or backward slash characters are interpreted as folder (directory) separators. Any required folder will be created as necessary. You can thus easily place your log files in separate folders. </p> <p>Just like <code>FixedWindowRollingPolicy</code>, <code>TimeBasedRollingPolicy</code> supports automatic file compression. This feature is enabled if the value of the <span class="prop">fileNamePattern</span> option ends with <em>.gz</em> or <em>.zip</em>. </p> <table class="bodyTable striped"> <tr class="a"> <th><span class="prop">fileNamePattern</span></th> <th>Rollover schedule</th> <th>Example</th> </tr> <tr> <td><em>/wombat/foo.%d.gz</em></td> <td>Daily rollover (at midnight) with automatic GZIP compression of the archived files.</td> <td> <p><span class="prop">file</span> property not set: During November 23rd, 2009, logging output will go to the file <em>/wombat/foo.2009-11-23</em>. However, at midnight that file will be compressed to become <em>/wombat/foo.2009-11-23.gz</em>. For the 24th of November, logging output will be directed to <em>/wombat/folder/foo.2009-11-24</em> until it's rolled over at the beginning of the next day. </p> <p><span class="prop">file</span> property set to /wombat/foo.txt: During November 23rd, 2009, logging output will go to the file <em>/wombat/foo.txt</em>. At midnight that file will be compressed and renamed as <em>/wombat/foo.2009-11-23.gz</em>. A new <em>/wombat/foo.txt</em> file will be created where logging output will go for the rest of November 24rd. At midnight November 24th, <em>/wombat/foo.txt</em> will be compressed and renamed as <em>/wombat/foo.2009-11-24.gz</em> and so on. </p> </td> </tr> </table> <p>The <span class="prop">fileNamePattern</span> serves a dual purpose. First, by studying the pattern, logback computes the requested rollover periodicity. Second, it computes each archived file's name. Note that it is possible for two different patterns to specify the same periodicity. The patterns <em>yyyy-MM</em> and <em>yyyy@MM</em> both specify monthly rollover, although the resulting archive files will carry different names. </p> <p>By setting the <span class="prop">file</span> property you can decouple the location of the active log file and the location of the archived log files. The logging output will be targeted into the file specified by the <span class="prop">file</span> property. It follows that the name of the active log file will not change over time. However, if you choose to omit the <span class="prop">file</span> property, then the active file will be computed anew for each period based on the value of <span class="prop">fileNamePattern</span>. By leaving the <span class="prop">file</span> option unset you can avoid file <a href="../codes.html#renamingError">renaming errors</a> which occur while there exist external file handles referencing log files during roll over. </p> <p>The <span class="prop">maxHistory</span> property controls the maximum number of archive files to keep, deleting older files. For example, if you specify monthly rollover, and set <span class="prop">maxHistory</span> to 6, then 6 months worth of archives files will be kept with files older than 6 months deleted. Note as old archived log files are removed, any folders which were created for the purpose of log file archiving will be removed as appropriate. </p> <p>For various technical reasons, rollovers are not clock-driven but depend on the arrival of logging events. For example, on 8th of March 2002, assuming the <span class="prop">fileNamePattern</span> is set to <em>yyyy-MM-dd</em> (daily rollover), the arrival of the first event after midnight will trigger a rollover. If there are no logging events during, say 23 minutes and 47 seconds after midnight, then rollover will actually occur at 00:23'47 AM on March 9th and not at 0:00 AM. Thus, depending on the arrival rate of events, rollovers might be triggered with some latency. However, regardless of the delay, the rollover algorithm is known to be correct, in the sense that all logging events generated during a certain period will be output in the correct file delimiting that period. </p> <p>Here is a sample configuration for <code>RollingFileAppender</code> in conjunction with a <code>TimeBasedRollingPolicy</code>. </p> <p class="example">Example: Sample configuration of a <code>RollingFileAppender</code> using a <code>TimeBasedRollingPolicy</code> (logback-examples/src/main/java/chapters/appenders/conf/logback-RollingTimeBased.xml)</p> <span class="asGroovy" onclick="return asGroovy('logback-RollingTimeBased');">View as .groovy</span> <pre id="logback-RollingTimeBased" class="prettyprint source"><configuration> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>logFile.log</file> <b><rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- daily rollover --> <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- keep 30 days' worth of history --> <maxHistory>30</maxHistory> </rollingPolicy></b> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="FILE" /> </root> </configuration></pre> <p>The next configuration sample illustrates the use of <code>RollingFileAppender</code> associated with <code>TimeBasedRollingPolicy</code> in <span class="prop">prudent</span> mode. </p> <p class="example">Example: Sample configuration of a <code>RollingFileAppender</code> using a <code>TimeBasedRollingPolicy</code> (logback-examples/src/main/java/chapters/appenders/conf/logback-PrudentTimeBasedRolling.xml)</p> <span class="asGroovy" onclick="return asGroovy('logback-PrudentTimeBasedRolling');">View as .groovy</span> <pre id="logback-PrudentTimeBasedRolling" class="prettyprint source"><configuration> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <b><!-- Support multiple-JVM writing to the same log file --></b> <b><prudent>true</prudent></b> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern> <maxHistory>30</maxHistory> </rollingPolicy> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="FILE" /> </root> </configuration></pre> <h4><a name="FixedWindowRollingPolicy" href="#FixedWindowRollingPolicy"><span class="anchor"/></a>FixedWindowRollingPolicy </h4> <p>When rolling over, <a href="../xref/ch/qos/logback/core/rolling/FixedWindowRollingPolicy.html"> <code>FixedWindowRollingPolicy</code></a> renames files according to a fixed window algorithm as described below. </p> <p>The <span class="prop">fileNamePattern</span> option represents the file name pattern for the archived (rolled over) log files. This option is required and must include an integer token <em>%i</em> somewhere within the pattern. </p> <p>Here are the available properties for <code>FixedWindowRollingPolicy</code> </p> <table class="bodyTable striped"> <tr> <th>Property Name</th> <th>Type</th> <th>Description</th> </tr> <tr> <td><span class="prop" container="fwrp">minIndex</span></td> <td><code>int</code></td> <td> <p>This option represents the lower bound for the window's index. </p> </td> </tr> <tr> <td><span class="prop" container="fwrp">maxIndex</span></td> <td><code>int</code></td> <td> <p>This option represents the upper bound for the window's index. </p> </td> </tr> <tr> <td><span class="prop" container="fwrp">fileNamePattern</span></td> <td><code>String</code></td> <td> <p>This option represents the pattern that will be followed by the <code>FixedWindowRollingPolicy</code> when renaming the log files. It must contain the string <em>%i</em>, which will indicate the position where the value of the current window index will be inserted. </p> <p>For example, using <em>MyLogFile%i.log</em> associated with minimum and maximum values of <em>1</em> and <em>3</em> will produce archive files named <em>MyLogFile1.log</em>, <em>MyLogFile2.log</em> and <em>MyLogFile3.log</em>. </p> <p>Note that file compression is also specified via this property. For example, <span class="prop">fileNamePattern</span> set to <em>MyLogFile%i.log.zip</em> means that archived files must be compressed using the <em>zip</em> format; <em>gz</em> format is also supported. </p> </td> </tr> </table> <p>Given that the fixed window rolling policy requires as many file renaming operations as the window size, large window sizes are strongly discouraged. When large values are specified by the user, the current implementation will automatically reduce the window size to 12. </p> <p>Let us go over a more concrete example of the fixed window rollover policy. Suppose that <span class="prop">minIndex</span> is set to <em>1</em>, <span class="prop">maxIndex</span> set to <em>3</em>, <span class="prop">fileNamePattern</span> property set to <em>foo%i.log</em>, and that <span class="prop">fileNamePattern</span> property is set to <em>foo.log</em>. </p> <table class="bodyTable striped"> <tr> <th>Number of rollovers</th> <th>Active output target</th> <th>Archived log files</th> <th>Description</th> </tr> <tr> <td>0</td> <td>foo.log</td> <td>-</td> <td>No rollover has happened yet, logback logs into the initial file. </td> </tr> <tr> <td>1</td> <td>foo.log</td> <td>foo1.log</td> <td>First rollover. <em>foo.log</em> is renamed as <em>foo1.log</em>. A new <em>foo.log</em> file is created and becomes the active output target. </td> </tr> <tr> <td>2</td> <td>foo.log</td> <td>foo1.log, foo2.log</td> <td>Second rollover. <em>foo1.log</em> is renamed as <em>foo2.log</em>. <em>foo.log</em> is renamed as <em>foo1.log</em>. A new <em>foo.log</em> file is created and becomes the active output target. </td> </tr> <tr> <td>3</td> <td>foo.log</td> <td>foo1.log, foo2.log, foo3.log</td> <td>Third rollover. <em>foo2.log</em> is renamed as <em>foo3.log</em>. <em>foo1.log</em> is renamed as <em>foo2.log</em>. <em>foo.log</em> is renamed as <em>foo1.log</em>. A new <em>foo.log</em> file is created and becomes the active output target. </td> </tr> <tr> <td>4</td> <td>foo.log</td> <td>foo1.log, foo2.log, foo3.log</td> <td>In this and subsequent rounds, the rollover begins by deleting <em>foo3.log</em>. Other files are renamed by incrementing their index as shown in previous steps. In this and subsequent rollovers, there will be three archive logs and one active log file. </td> </tr> </table> <p>The configuration file below gives an example of configuring <code>RollingFileAppender</code> and <code>FixedWindowRollingPolicy</code>. Note that the <span class="prop">File</span> option is mandatory even if it contains some of the same information as conveyed with the <span class="prop">fileNamePattern</span> option. </p> <p class="example">Example: Sample configuration of a <code>RollingFileAppender</code> using a <code>FixedWindowRollingPolicy</code> (logback-examples/src/main/java/chapters/appenders/conf/logback-RollingFixedWindow.xml)</p> <span class="asGroovy" onclick="return asGroovy('logback-RollingFixedWindow');">View as .groovy</span> <pre id="logback-RollingFixedWindow" class="prettyprint source"><configuration> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <b><file>test.log</file></b> <b><rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <fileNamePattern>tests.%i.log.zip</fileNamePattern> <minIndex>1</minIndex> <maxIndex>3</maxIndex> </rollingPolicy></b> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <maxFileSize>5MB</maxFileSize> </triggeringPolicy> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="FILE" /> </root> </configuration></pre> <h3> <a name="SizeAndTimeBasedFNATP" href="#SizeAndTimeBasedFNATP"><span class="anchor"/></a>Size <b>and</b> time based archiving </h3> <p>Sometimes you may wish to archive files essentially by date but at the same time limit the size of each log file, in particular if post-processing tools impose size limits on the log files. In order to address this requirement, logback ships with a sub-component for <code>TimeBasedRollingPolicy</code> called <code>SizeAndTimeBasedFNATP</code>, where FNATP stands for File Naming And Triggering Policy.</p> <p>Here is a sample configuration file demonstrating time and size based log file archiving.</p> <p class="example">Example: Sample configuration for <code>SizeAndTimeBasedFNATP</code> (logback-examples/src/main/java/chapters/appenders/conf/logback-sizeAndTime.xml)</p> <span class="asGroovy" onclick="return asGroovy('logback-sizeAndTime');">View as .groovy</span> <pre id="logback-sizeAndTime" class="prettyprint source"><configuration> <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>mylog.txt</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- rollover daily --> <fileNamePattern><b>mylog-%d{yyyy-MM-dd}.<span class="big">%i</span>.txt</b></fileNamePattern> <b><timeBasedFileNamingAndTriggeringPolicy</b> <b>class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"></b> <!-- or whenever the file size reaches 100MB --> <b><maxFileSize>100MB</maxFileSize></b> <b></timeBasedFileNamingAndTriggeringPolicy></b> </rollingPolicy> <encoder> <pattern>%msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="ROLLING" /> </root> </configuration></pre> <p>Note the "%i" conversion token in addition to "%d". Each time the current log file reaches <span class="prop">maxFileSize</span> before the current time period ends, it will be archived with an increasing index, starting at 0.</p> <p>Size and time based archiving supports deletion of old archive files. You need to specify the number of periods to preserve with the <span class="prop">maxHistory</span> property. When your application is stopped and restarted, logging will continue at the correct location, i.e. at the largest index number for the current period. </p> <h2> <a name="TriggeringPolicy" href="#TriggeringPolicy">Overview of triggering policies</a> </h2> <p><a href="../xref/ch/qos/logback/core/rolling/TriggeringPolicy.html"><code>TriggeringPolicy</code></a> implementations are responsible for instructing the <code>RollingFileAppender</code> when to rollover.</p> <p>The <code>TriggeringPolicy</code> interface contains only one method.</p> <pre class="prettyprint source">package ch.qos.logback.core.rolling; import java.io.File; import ch.qos.logback.core.spi.LifeCycle; public interface TriggeringPolicy<E> extends LifeCycle { <b>public boolean isTriggeringEvent(final File activeFile, final <E> event);</b> }</pre> <p>The <code>isTriggeringEvent()</code> method takes as parameters the active file and the logging event currently being processed. The concrete implementation determines whether the rollover should occur or not, based on these parameters. </p> <p>The most widely-used triggering policy, namely <code>TimeBasedRollingPolicy</code> which also doubles as a rolling policy, was already <a href="#TimeBasedRollingPolicy">discussed earlier</a> along with other rolling policies. </p> <h4><a name="SizeBasedTriggeringPolicy" href="#SizeBasedTriggeringPolicy">SizeBasedTriggeringPolicy</a></h4> <p><a href="../xref/ch/qos/logback/core/rolling/SizeBasedTriggeringPolicy.html"> <code>SizeBasedTriggeringPolicy</code></a> looks at the size of the currently active file. If it grows larger than the specified size, it will signal the owning <code>RollingFileAppender</code> to trigger the rollover of the existing active file. </p> <p><code>SizeBasedTriggeringPolicy</code> accepts only one parameter, namely <span class="prop">maxFileSize</span>, with a default value of 10 MB. </p> <p>The <span class="prop">maxFileSize</span> option can be specified in bytes, kilobytes, megabytes or gigabytes by suffixing a numeric value with <em>KB</em>, <em>MB</em> and respectively <em>GB</em>. For example, <em>5000000</em>, <em>5000KB</em>, <em>5MB</em> and <em>2GB</em> are all valid values, with the first three being equivalent. </p> <p>Here is a sample configuration with a <code>RollingFileAppender</code> in conjunction with <code>SizeBasedTriggeringPolicy</code> triggering rollover when the log file reaches 5MB in size. </p> <p class="example">Example: Sample configuration of a <code>RollingFileAppender</code> using a <code>SizeBasedTriggeringPolicy</code> (logback-examples/src/main/java/chapters/appenders/conf/logback-RollingSizeBased.xml)</p> <span class="asGroovy" onclick="return asGroovy('logback-RollingSizeBased');">View as .groovy</span> <pre id="logback-RollingSizeBased" class="prettyprint source"><configuration> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>test.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <fileNamePattern>test.%i.log.zip</fileNamePattern> <minIndex>1</minIndex> <maxIndex>3</maxIndex> </rollingPolicy> <b><triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <maxFileSize>5MB</maxFileSize> </triggeringPolicy></b> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="FILE" /> </root> </configuration></pre> <!-- XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx --> <a name="Classic"></a> <h2>Logback Classic</h2> <p>While logging events are generic in logback-core, within logback-classic they are always instances of <code>ILoggingEvent</code>. Logback-classic is nothing more than a specialized processing pipeline handling instances of <code>ILoggingEvent</code>. </p> <h3> <a name="SocketAppender" href="#SocketAppender"><span class="anchor"/></a>SocketAppender </h3> <p>The appenders covered thus far are only able to log to local resources. In contrast, the <a href="../xref/ch/qos/logback/classic/net/SocketAppender.html"> <code>SocketAppender</code></a> is designed to log to a remote entity by transmitting serialized <code>ILoggingEvent</code> instances over the wire. The actual type of the serialized event is <a href="../xref/ch/qos/logback/classic/spi/LoggingEventVO.html"><code>LoggingEventVO</code></a> which implements the <code>ILoggingEvent</code> interface. Nevertheless, remote logging is non-intrusive as far as the logging event is concerned. On the receiving end after deserialization, the event can be logged as if it were generated locally. Multiple <code>SocketAppender</code> instances running on different machines can direct their logging output to a central log server whose format is fixed. <code>SocketAppender</code> does not take an associated layout because it sends serialized events to a remote server. <code>SocketAppender</code> operates above the <em>Transmission Control Protocol (TCP)</em> layer which provides a reliable, sequenced, flow-controlled end-to-end octet stream. Consequently, if the remote server is reachable, then log events will eventually arrive there. Otherwise, if the remote server is down or unreachable, the logging events will simply be dropped. If and when the server comes back up, then event transmission will be resumed transparently. This transparent reconnection is performed by a connector thread which periodically attempts to connect to the server. </p> <p>Logging events are automatically buffered by the native TCP implementation. This means that if the link to server is slow but still faster than the rate of event production by the client, the client will not be affected by the slow network connection. However, if the network connection is slower than the rate of event production, then the client can only progress at the network rate. In particular, in the extreme case where the network link to the server is down, the client will be eventually blocked. Alternatively, if the network link is up, but the server is down, the client will not be blocked, although the log events will be lost due to server unavailability. </p> <p>Even if a <code>SocketAppender</code> is no longer attached to any logger, it will not be garbage collected in the presence of a connector thread. A connector thread exists only if the connection to the server is down. To avoid this garbage collection problem, you should close the <code>SocketAppender</code> explicitly. Long lived applications which create/destroy many <code>SocketAppender</code> instances should be aware of this garbage collection problem. Most other applications can safely ignore it. If the JVM hosting the <code>SocketAppender</code> exits before the <code>SocketAppender</code> is closed, either explicitly or subsequent to garbage collection, then there might be untransmitted data in the pipe which may be lost. This is a common problem on Windows based systems. To avoid lost data, it is usually sufficient to <code>close()</code> the <code>SocketAppender</code> either explicitly or by calling the <code>LoggerContext</code>'s <code>stop()</code> method before exiting the application. </p> <p>The remote server is identified by the <span class="prop">remoteHost</span> and <span class="prop">port</span> properties. <code>SocketAppender</code> properties are listed in the following table. </p> <table class="bodyTable striped"> <tr> <th>Property Name</th> <th>Type</th> <th>Description</th> </tr> <tr> <td><span class="prop" container="socket">includeCallerData</span></td> <td><code>boolean</code></td> <td> <p> The <span class="prop" container="socket">includeCallerData</span> option takes a boolean value. If true, the caller data will be available to the remote host. By default no caller data is sent to the server. </p> </td> </tr> <tr> <td><span class="prop" container="socket">port</span></td> <td><code>int</code></td> <td> <p> The port number of the remote server. </p> </td> </tr> <tr> <td><span class="prop" container="socket">reconnectionDelay</span></td> <td><code>int</code></td> <td> The <span class="prop">reconnectionDelay</span> option takes a positive integer representing the number of milliseconds to wait between each failed connection attempt to the server. The default value of this option is 30'000 which corresponds to 30 seconds. Setting this option to zero turns off reconnection capability. Note that in case of successful connection to the server, there will be no connector thread present. </td> </tr> <tr> <td><span class="prop" container="socket">remoteHost</span></td> <td><code>String</code></td> <td> The host name of the server. </td> </tr> </table> <p>The standard logback distribution includes a simple log server application named <code>ch.qos.logback.classic.net.SimpleSocketServer</code> that can service multiple <code>SocketAppender</code> clients. It waits for logging events from <code>SocketAppender</code> clients. After reception by <code>SimpleSocketServer</code>, the events are logged according to local server policy. The <code>SimpleSocketServer</code> application takes two parameters: port and configFile; where port is the port to listen on and configFile is a configuration script in XML format. </p> <p> Assuming you are in the <em>logback-examples/</em> directory, start <code>SimpleSocketServer</code> with the following command: </p> <p class="source">java ch.qos.logback.classic.net.SimpleSocketServer 6000 \ src/main/java/chapters/appenders/socket/server1.xml</p> <p>where 6000 is the port number to listen on and <em>server1.xml</em> is a configuration script that adds a <code>ConsoleAppender</code> and a <code>RollingFileAppender</code> to the root logger. After you have started <code>SimpleSocketServer</code>, you can send it log events from multiple clients using <code>SocketAppender</code>. The examples associated with this manual include two such clients: <code>chapters.appenders.SocketClient1</code> and <code>chapters.appenders.SocketClient2</code> Both clients wait for the user to type a line of text on the console. The text is encapsulated in a logging event of level debug and then sent to the remote server. The two clients differ in the configuration of the <code>SocketAppender</code>. <code>SocketClient1</code> configures the appender programmatically while <code>SocketClient2</code> requires a configuration file. </p> <p>Assuming <code>SimpleSocketServer</code> is running on the local host, you connect to it with the following command: </p> <p class="source">java chapters.appenders.socket.SocketClient1 localhost 6000</p> <p>Each line that you type should appear on the console of the <code>SimpleSocketServer</code> launched in the previous step. If you stop and restart the <code>SimpleSocketServer</code> the client will transparently reconnect to the new server instance, although the events generated while disconnected will be simply (and irrevocably) lost. </p> <p> Unlike <code>SocketClient1</code>, the sample application <code>SocketClient2</code> does not configure logback by itself. It requires a configuration file in XML format. The configuration file <em>client1.xml</em> shown below creates a <code>SocketAppender</code> and attaches it to the root logger. </p> <p class="example">Example: SocketAppender configuration (logback-examples/src/main/java/chapters/appenders/socket/client1.xml)</p> <span class="asGroovy" onclick="return asGroovy('client1');">View as .groovy</span> <pre id="client1" class="prettyprint source"><configuration> <appender name="SOCKET" class="ch.qos.logback.classic.net.SocketAppender"> <remoteHost>${host}</remoteHost> <port>${port}</port> <reconnectionDelay>10000</reconnectionDelay> <includeCallerData>${includeCallerData}</includeCallerData> </appender> <root level="DEBUG"> <appender-ref ref="SOCKET" /> </root> </configuration></pre> <p> Note that in the above configuration scripts the values for the <span class="prop">remoteHost</span>, <span class="prop">port</span> and <span class="prop">includeCallerData</span> properties are not given directly but as substituted variable keys. The values for the variables can be specified as system properties: </p> <p class="source">java -Dhost=localhost -Dport=6000 -DincludeCallerData=false \ chapters.appenders.socket.SocketClient2 src/main/java/chapters/appenders/socket/client1.xml</p> <p>This command should give similar results to the previous <code>SocketClient1</code> example. </p> <p>Allow us to repeat for emphasis that serialization of logging events is not intrusive. A deserialized event carries the same information as any other logging event. It can be manipulated as if it were generated locally; except that serialized logging events by default do not include caller data. Here is an example to illustrate the point. First, start <code>SimpleSocketServer</code> with the following command: </p> <p class="source"> java ch.qos.logback.classic.net.SimpleSocketServer 6000 \ src/main/java/chapters/appenders/socket/server2.xml</p> <p>The configuration file <em>server2.xml</em> creates a <code>ConsoleAppender</code> whose layout outputs the caller's file name and line number along with other information. If you run <code>SocketClient2</code> with the configuration file <em>client1.xml</em> as previously, you will notice that the output on the server side will contain two question marks between parentheses instead of the file name and the line number of the caller: </p> <p class="source">2006-11-06 17:37:30,968 DEBUG [Thread-0] [?:?] chapters.appenders.socket.SocketClient2 - Hi</p> <p>The outcome can be easily changed by instructing the <code>SocketAppender</code> to include caller data by setting the <span class="prop">includeCallerData</span> option to true. Using the following command will do the trick: </p> <pre class="source">java -Dhost=localhost -Dport=6000 -DincludeCallerData=true \ chapters.appenders.socket.SocketClient2 src/main/java/chapters/appenders/socket/client1.xml</pre> <p>As deserialized events can be handled in the same way as locally generated events, they even can be sent to a second server for further treatment. As an exercise, you may wish to setup two servers where the first server tunnels the events it receives from its clients to a second server. </p> <h3 class="doAnchor">SMTPAppender</h3> <p>The <a href="../xref/ch/qos/logback/classic/net/SMTPAppender.html"><code>SMTPAppender</code></a> accumulates logging events in one or more fixed-size buffers and sends the contents of the appropriate buffer in an email after a user-specified event occurs. SMTP email transmission (sending) is performed asynchronously. By default, the email transmission is triggered by a logging event of level ERROR. Moreover, by default, a single buffer is used for all events. </p> <p>The various properties for <code>SMTPAppender</code> are summarized in the following table. </p> <table class="bodyTable striped"> <tr> <th>Property Name</th> <th>Type</th> <th>Description</th> </tr> <tr> <td><span class="prop" container="smtp">smtpHost</span></td> <td><code>String</code></td> <td>The host name of the SMTP server. This parameter is mandatory.</td> </tr> <tr> <td><span class="prop" container="smtp">smtpPort</span></td> <td><code>int</code></td> <td>The port where the SMTP server is listening. Defaults to 25.</td> </tr> <tr> <td><span class="prop" name="smtpTo">to</span></td> <td><code>String</code></td> <td>The email address of the recipient as a <em>pattern</em>. The pattern is evaluated anew with the triggering event as input for each outgoing email. Multiple recipients can be specified by separating the destination addresses with commas. Alternatively, multiple recipients can also be specified by using multiple <code><to></code> elements. </td> </tr> <tr> <td><span class="prop" container="smtp">from</span></td> <td><code>String</code></td> <td>The originator of the email messages sent by <code>SMTPAppender</code> in the <a href="http://en.wikipedia.org/wiki/Email_address">usual email address format</a>. If you wish to include the sender's name, then use the format "Adam Smith &lt;smith@moral.org&gt;" so that the message appears as originating from "Adam Smith <smith@moral.org>". </td> </tr> <tr> <td><span class="prop">subject</span></td> <td><code>String</code></td> <td> <p>The subject of the email. It can be any value accepted as a valid conversion pattern by <a href="layouts.html#ClassicPatternLayout">PatternLayout</a>. Layouts will be discussed in the next chapter. </p> <p>The outgoing email message will have a subject line corresponding to applying the pattern on the logging event that triggered the email message. </p> <p>Assuming the <span class="prop">subject</span> option is set to "Log: %logger - %msg" and the triggering event's logger is named "com.foo.Bar", and contains the message "Hello world", then the outgoing email will have the subject line "Log: com.foo.Bar - Hello World". </p> <p>By default, this option is set to "%logger{20} - %m".</p> </td> </tr> <tr> <td><span class="prop" container="smtp">discriminator</span></td> <td><code><a href="../xref/ch/qos/logback/core/sift/Discriminator.html">Discriminator</a></code></td> <td> <p>With the help of a <span class="prop">Discriminator</span>, <code>SMTPAppender</code> can scatter incoming events into different buffers according to the value returned by the discriminator. The default discriminator always returns the same value so that the same buffer is used for all events. </p> <p>By specifying a discriminator other than the default one, it is possible to receive email messages containing a events pertaining to a particular user, user session or client IP address. </p> </td> </tr> <tr> <td><span class="prop" name="smtpAppender_Evaluator">evaluator</span></td> <td><code><a href="../xref/ch/qos/logback/classic/boolex/IEvaluator.html">IEvaluator</a></code></td> <td> <p>This option is declared by creating a new <code><EventEvaluator/></code> element. The name of the class that the user wishes to use as the <code>SMTPAppender</code>'s <code>Evaluator</code> needs to be specified via the <span class="attr">class</span> attribute. </p> <p>In the absence of this option, <code>SMTPAppender</code> is assigned an instance of <a href="../xref/ch/qos/logback/classic/boolex/OnErrorEvaluator.html">OnErrorEvaluator</a> which triggers email transmission when it encounters an event of level <em>ERROR</em> or higher. </p> <!-- <p><code>EventEvaluator</code> objects are subclasses of the <code>JaninoEventEvaluatorBase</code> which depends on Janino. See the <a href="../dependencies.html">dependencies page</a> for more information. </p> --> <p>Logback ships with several other evaluators, namely <a href="../xref/ch/qos/logback/classic/boolex/OnMarkerEvaluator.html"><code>OnMarkerEvaluator</code></a> (discussed below) and a powerful evaluator called <a href="../xref/ch/qos/logback/classic/boolex/JaninoEventEvaluator.html"><code>JaninoEventEvaluator</code></a>, discussed in <a href="filters.html#evalutatorFilter">another chapter</a>. The more recent versions of logback ship with an even more powerful evaluator called <a href="filters.html#GEventEvaluator"><code>GEventEvaluator</code></a>. </p> </td> </tr> <tr> <td valign="top"><span class="prop" container="smtp">cyclicBufferTracker</span></td> <td><a href="../xref/ch/qos/logback/core/spi/CyclicBufferTracker.html"><code>CyclicBufferTracker</code></a> </td> <td> <p>As the name indicates, an instance of the <code>CyclicBufferTracker</code> class tracks cyclic buffers. It does so based on the keys returned by the <span class="prop">discriminator</span> (see above). </p> <p>If you don't specify a <span class="prop">cyclicBufferTracker</span>, an instance of <a href="../xref/ch/qos/logback/core/spi/CyclicBufferTrackerImpl.html">CyclicBufferTrackerImpl</a> will be automatically created. By default, this instance will keep events in a cyclic buffer of size 256. You may change the size with the help of the <span class="prop">bufferSize</span> option (see below).</p> </td> </tr> <tr> <td><span class="prop" container="smtp">username</span></td> <td><code>String</code></td> <td>The username value to use during plain user/password authentication. By default, this parameter is null. </td> </tr> <tr class="alt"> <td><span class="prop" container="smtp">password</span></td> <td><code>String</code></td> <td>The password value to use for plain user/password authentication. By default, this parameter is null. </td> </tr> <tr> <td><span class="prop" container="smtp">STARTTLS</span> </td> <td><code>boolean</code></td> <td>If this parameter is set to true, then this appender will issue the STARTTLS command (if the server supports it) causing the connection to switch to SSL. Note that the connection is initially non-encrypted. By default, this parameter is set to false. </td> </tr> <tr> <td><span class="prop" container="smtp">SSL</span></td> <td><code>boolean</code></td> <td>If this parameter is set to true, then this appender will open an SSL connection to the server. By default, this parameter is set to false. </td> </tr> <tr> <td><span class="prop" container="smtp">charsetEncoding</span></td> <td><code>String</code></td> <td>The outgoing email message will be encoded in the designated <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/nio/charset/Charset.html">charset</a>. The default charset encoding is "UTF-8" which works well for most purposes. </td> </tr> <tr> <td><span class="prop" container="smtp">localhost</span></td> <td><code>String</code></td> <td>In case the hostname of the SMTP client is not properly configured, e.g. if the client hostname is not fully qualified, certain SMTP servers may reject the HELO/EHLO commands sent by the client. To overcome this issue, you may set the value of the <span class="prop">localhost</span> property to the fully qualified name of the client host. See also the "mail.smtp.localhost" property in the documentation for the <a href="http://javamail.kenai.com/nonav/javadocs/com/sun/mail/smtp/package-summary.html">com.sun.mail.smtp</a> package.</td> </tr> <tr> <td><span class="prop" container="smtp">asynchronousSending</span></td> <td><code>boolean</code></td> <td>This property determines whether email transmission is done asynchronously or not. By default, the <span class="prop">asynchronousSending</span> property is 'true'. However, under certain circumstances asynchronous sending may be inappropriate. For example if your application uses <code>SMTPAppender</code> to send alerts in response to a fatal error, and then exits, the relevant thread may not have the time to send the alert email. In this case, set <span class="prop">asynchronousSending</span> property to 'false' for synchronous email transmission. </td> </tr> <tr> <td><span class="prop" container="smtp">includeCallerData</span></td> <td><code>boolean</code></td> <td>By default, <span class="prop">includeCallerData</span> is set to <code>false</code>. You should set <span class="prop">includeCallerData</span> to <code>true</code> if <span class="prop">asynchronousSending</span> is enabled and you wish to include caller data in the logs. </td> </tr> <tr> <td><span class="prop" container="smtp">sessionViaJNDI</span></td> <td><code>boolean</code></td> <td><code>SMTPAppender</code> relies on <code>javax.mail.Session</code> to send out email messages. By default, <span class="prop">sessionViaJNDI</span> is set to <code>false</code> so the <code>javax.mail.Session</code> instance is built by <code>SMTPAppender</code> itself with the properties specified by the user. If the <span class="prop">sessionViaJNDI</span> property is set to <code>true</code>, the <code>javax.mail.Session</code> object will be retrieved via JNDI. See also the <span class="prop">jndiLocation</span> property. <p>Retrieving the <code>Session</code> via JNDI can reduce the number of places you need to configure/reconfigure the same information, making your application <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">dryer</a>. For more information on configuring resources in Tomcat see <a href="http://tomcat.apache.org/tomcat-6.0-doc/jndi-resources-howto.html#JavaMail_Sessions">JNDI Resources How-to</a>. <span class="label">beware</span> As noted in that document, make sure to remove <em>mail.jar</em> and <em>activation.jar</em> from your web-applications <em>WEB-INF/lib</em> folder when retrieving the <code>Session</code> from JNDI. </p> </td> </tr> <tr> <td><span class="prop" container="smtp">jndiLocation</span></td> <td><code>String</code></td> <td>The location where the javax.mail.Session is placed in JNDI. By default, <span class="prop">jndiLocation</span> is set to <span style="white-space:nowrap">"java:comp/env/mail/Session"</span>. </td> </tr> </table> <p>The <code>SMTPAppender</code> keeps only the last 256 logging events in its cyclic buffer, throwing away older events when its buffer becomes full. Thus, the number of logging events delivered in any e-mail sent by <code>SMTPAppender</code> is upper-bounded by 256. This keeps memory requirements bounded while still delivering a reasonable amount of application context. </p> <p>The <code>SMTPAppender</code> relies on the JavaMail API. It has been tested with JavaMail API version 1.4. The JavaMail API requires the JavaBeans Activation Framework package. You can download the <a href="http://java.sun.com/products/javamail/">JavaMail API</a> and the <a href="http://java.sun.com/beans/glasgow/jaf.html">JavaBeans Activation Framework</a> from their respective websites. Make sure to place these two jar files in the classpath before trying the following examples. </p> <p>A sample application, <a href="../xref/chapters/appenders/mail/EMail.html"><code>chapters.appenders.mail.EMail</code></a> generates a number of log messages followed by a single error message. It takes two parameters. The first parameter is an integer corresponding to the number of logging events to generate. The second parameter is the logback configuration file. The last logging event generated by <em>EMail</em> application, an ERROR, will trigger the transmission of an email message. </p> <p>Here is a sample configuration file intended for the <code>Email</code> application: </p> <p class="example">Example: A sample <code>SMTPAppender</code> configuration (logback-examples/src/main/java/chapters/appenders/mail/mail1.xml)</p> <span class="asGroovy" onclick="return asGroovy('mail1');">View as .groovy</span> <pre id="mail1" class="prettyprint source"><configuration> <appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender"> <smtpHost>ADDRESS-OF-YOUR-SMTP-HOST</smtpHost> <to>EMAIL-DESTINATION</to> <to>ANOTHER_EMAIL_DESTINATION</to> <!-- additional destinations are possible --> <from>SENDER-EMAIL</from> <subject>TESTING: %logger{20} - %m</subject> <layout class="ch.qos.logback.classic.PatternLayout"> <pattern>%date %-5level %logger{35} - %message%n</pattern> </layout> </appender> <root level="DEBUG"> <appender-ref ref="EMAIL" /> </root> </configuration></pre> <p>Before trying out <code>chapters.appenders.mail.Email</code> application with the above configuration file, you must set the <span class="prop">smtpHost</span>, <span class="prop">to</span> and <span class="prop">from</span> properties to values appropriate for your environment. Once you have set the correct values in the configuration file, execute the following command: </p> <div class="source"><pre>java chapters.appenders.mail.EMail 100 src/main/java/chapters/appenders/mail/mail1.xml</pre></div> <p>The recipient you specified should receive an email message containing 100 logging events formatted by <code>PatternLayout</code> The figure below is the resulting email message as shown by Mozilla Thunderbird. </p> <p><img src="images/chapters/appenders/smtpAppender1.jpg" alt="resulting email"/></p> <p>In the next example configuration file <em>mail2.xml</em>, the values for the <span class="prop">smtpHost</span>, <span class="prop">to</span> and <span class="prop">from</span> properties are determined by variable substitution. Here is the relevant part of <em>mail2.xml</em>. </p> <pre class="prettyprint source"><appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender"> <smtpHost>${smtpHost}</smtpHost> <to>${to}</to> <from>${from}</from> <layout class="ch.qos.logback.classic.html.HTMLLayout"/> </appender></pre> <p>You can pass the required parameters on the command line:</p> <div class="source"><pre>java -Dfrom=source@xyz.com -Dto=recipient@xyz.com -DsmtpHost=some_smtp_host \ chapters.appenders.mail.EMail 10000 src/main/java/chapters/appenders/mail/mail2.xml </pre></div> <p>Be sure to replace with values as appropriate for your environment. </p> <p>Note that in this latest example, <code>PatternLayout</code> was replaced by <code>HTMLLayout</code> which formats logs as an HTML table. You can change the list and order of columns as well as the CSS of the table. Please refer to <a href="layouts.html#ClassicHTMLLayout">HTMLLayout</a> documentation for further details. </p> <p>Given that the size of the cyclic buffer is 256, the recipient should see an email message containing 256 events conveniently formatted in an HTML table. Note that this run of the <code>chapters.appenders.mail.Email</code> application generated 10'000 events of which only the last 256 were included in the outgoing email. </p> <p><img src="images/chapters/appenders/smtpAppender2.jpg" alt="2nd email"/></p> <p>Email clients such as Mozilla Thunderbird, Eudora or MS Outlook, offer reasonably good CSS support for HTML email. However, they sometimes automatically downgrade HTML to plaintext. For example, to view HTML email in Thunderbird, the "View→Message Body As→Original HTML" option must be set. Yahoo! Mail's support for HTML email, in particular its CSS support is very good. Gmail on the other hand, while it honors the basic HTML table structure, ignores the internal CSS formatting. Gmail supports inline CSS formatting but since inline CSS would make the resulting output too voluminous, <code>HTMLLayout</code> does not use inline CSS. </p> <h3><a name="cyclicBufferSize" href="#cyclicBufferSize"><span class="anchor"/></a>Custom buffer size</h3> <p>By default, the outgoing message will contain the last 256 messages seen by <code>SMTPAppender</code>. If your heart so desires, you may set a different buffer size as shown in the next example. </p> <p class="example">Example: <code>SMTPAppender</code> configuration with a custom bufer size (logback-examples/src/main/java/chapters/appenders/mail/customBufferSize.xml)</p> <pre class="prettyprint source"><configuration> <appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender"> <smtpHost>${smtpHost}</smtpHost> <to>${to}</to> <from>${from}</from> <subject>%logger{20} - %m</subject> <layout class="ch.qos.logback.classic.html.HTMLLayout"/> <b><cyclicBufferTracker class="ch.qos.logback.core.spi.CyclicBufferTrackerImpl"></b> <b><!-- send just one log entry per email --></b> <b><bufferSize>1</bufferSize></b> <b></cyclicBufferTracker></b> </appender> <root level="DEBUG"> <appender-ref ref="EMAIL" /> </root> </configuration> </pre> <h3 class="doAnchor">Triggering event</h3> <p>If the Evaluator property is not set, the <code>SMTPAppender</code> defaults to an <a href="../xref/ch/qos/logback/classic/boolex/OnErrorEvaluator.html">OnErrorEvaluator</a> instance which triggers email transmission when it encounters an event of level ERROR. While triggering an outgoing email in response to an error is relatively reasonable, it is possible to override this default behavior by providing a different implementation of the <code>EventEvaluator</code> interface. </p> <p>The <code>SMTPAppender</code> submits each incoming event to its evaluator by calling <code>evaluate()</code> method in order to check whether the event should trigger an email or just be placed in the cyclic buffer. When the evaluator gives a positive answer to its evaluation, an email is sent out. The <code>SMTPAppender</code> contains one and only one evaluator object. This object may manage its own internal state. For illustrative purposes, the <code>CounterBasedEvaluator</code> class listed next implements an event evaluator whereby every 1024th event triggers an email message. </p> <p class="example">Example: A <code>EventEvaluator</code> implementation that evaluates to <code>true</code> every 1024th event (<a href="../xref/chapters/appenders/mail/CounterBasedEvaluator.html">logback-examples/src/main/java/chapters/appenders/mail/CounterBasedEvaluator.java</a>)</p> <pre class="prettyprint source">package chapters.appenders.mail; import ch.qos.logback.core.boolex.EvaluationException; import ch.qos.logback.core.boolex.EventEvaluator; import ch.qos.logback.core.spi.ContextAwareBase; public class CounterBasedEvaluator extends ContextAwareBase implements EventEvaluator { static int LIMIT = 1024; int counter = 0; String name; <b>public boolean evaluate(Object event) throws NullPointerException, EvaluationException { counter++; if (counter == LIMIT) { counter = 0; return true; } else { return false; } }</b> public String getName() { return name; } public void setName(String name) { this.name = name; } }</pre> <p>Note that this class extends <code>ContextAwareBase</code> and implements <code>EventEvaluator</code>. This allows the user to concentrate on the core functions of her <code>EventEvaluator</code> and let the base class provide the common functionality. </p> <p>Setting the <span class="prop">Evaluator</span> option of <code>SMTPAppender</code> instructs it to use a custom evaluator. The next configuration file attaches a <code>SMTPAppender</code> to the root logger. This appender uses a <code>CounterBasedEvaluator</code> instance as its event evaluator. </p> <p class="example">Example: <code>SMTPAppender</code> with custom <code>Evaluator</code> and buffer size (logback-examples/src/main/java/chapters/appenders/mail/mail3.xml)</p> <span class="asGroovy" onclick="return asGroovy('mail3');">View as .groovy</span> <pre id="mail3" class="prettyprint source"><configuration> <appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender"> <b><evaluator class="chapters.appenders.mail.CounterBasedEvaluator" /></b> <smtpHost>${smtpHost}</smtpHost> <to>${to}</to> <from>${from}</from> <subject>%logger{20} - %m</subject> <layout class="ch.qos.logback.classic.html.HTMLLayout"/> </appender> <root level="DEBUG"> <appender-ref ref="EMAIL" /> </root> </configuration></pre> <h3 class="doAnchor" name="OnMarkerEvaluator">Marker based triggering </h3> <p>Although reasonable, the default triggering policy whereby every event of level ERROR triggers an outgoing email may result in too many emails, cluttering the targeted user's mailbox. Logback ships with another triggering policy, called <a href="../xref/ch/qos/logback/classic/boolex/OnMarkerEvaluator.html">OnMarkerEvaluator</a>. It is based on markers. In essence, emails are triggered only if the event is marked with a user-specified marker. The next example should make the point clearer. </p> <p>The <a href="../xref/chapters/appenders/mail/Marked_EMail.html">Marked_EMail</a> application contains several logging statements some of which are of level ERROR. One noteworthy statement contains a marker. Here is the relevant code. </p> <pre class="prettyprint source">Marker notifyAdmin = MarkerFactory.getMarker("NOTIFY_ADMIN"); logger.error(<b>notifyAdmin</b>, "This is a serious an error requiring the admin's attention", new Exception("Just testing"));</pre> <p>The next configuration file will trigger outgoing emails only in presence of events bearing the NOTIFY_ADMIN or the TRANSACTION_FAILURE markers. </p> <p class="example">Example: <code>SMTPAppender</code> with <code>OnMarkerEvaluator</code> (logback-examples/src/main/java/chapters/appenders/mail/mailWithMarker.xml)</p> <span class="asGroovy" onclick="return asGroovy('mailWithMarker');">View as .groovy</span> <pre id="mailWithMarker" class="prettyprint source"><configuration> <appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender"> <b><evaluator class="ch.qos.logback.classic.boolex.OnMarkerEvaluator"> <marker>NOTIFY_ADMIN</marker> <!-- you specify add as many markers as you want --> <marker>TRANSACTION_FAILURE</marker> </evaluator></b> <smtpHost>${smtpHost}</smtpHost> <to>${to}</to> <from>${from}</from> <layout class="ch.qos.logback.classic.html.HTMLLayout"/> </appender> <root> <level value ="debug"/> <appender-ref ref="EMAIL" /> </root> </configuration></pre> <p>Give it a whirl with the following command:</p> <pre class="source">java -Dfrom=source@xyz.com -Dto=recipient@xyz.com -DsmtpHost=some_smtp_host \ chapters.appenders.mail.Marked_EMail src/main/java/chapters/appenders/mail/mailWithMarker.xml</pre> <h4><a name="marker_JaninoEventEvaluator" href="#marker_JaninoEventEvaluator"><span class="anchor"/></a>Marker-based triggering with JaninoEventEvaluator</h4> <p>Note that instead of using the marker-centric <code>OnMarkerEvaluator</code>, we could use the much more generic <a href="filters.html#JaninoEventEvaluator"><code>JaninoEventEvaluator</code></a> or its even more powerful cousin <a href="filters.html#GEventEvaluator"><code>GEventEvaluator</code></a>. For example, the following configuration file uses <code>JaninoEventEvaluator</code> instead of <code>OnMarkerEvaluator</code> but is otherwise equivalent to the previous configuration file. </p> <p class="example">Example: <code>SMTPAppender</code> with <code>JaninoEventEvaluator</code> (logback-examples/src/main/java/chapters/appenders/mail/mailWithMarker_Janino.xml)</p> <span class="asGroovy" onclick="return asGroovy('mailWithMarker_Janino');">View as .groovy</span> <pre id="mailWithMarker_Janino" class="prettyprint source"><configuration> <appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender"> <evaluator class="ch.qos.logback.classic.boolex.JaninoEventEvaluator"> <expression> (marker != null) && (marker.contains("NOTIFY_ADMIN") || marker.contains("TRANSACTION_FAILURE")) </expression> </evaluator> ... same as above </appender> </configuration></pre> <h4><a name="marker_GEventEvaluator" href="#marker_GEventEvaluator"><span class="anchor"/></a>Marker-based triggering with GEventEvaluator</h4> <p>Here is the equivalent evaluator using <a href="filters.html#GEventEvaluator">GEventEvaluator</a>.</p> <p class="example">Example: the same with <code>GEventEvaluator</code> (logback-examples/src/main/java/chapters/appenders/mail/mailWithMarker_GEvent.xml)</p> <span class="asGroovy" onclick="return asGroovy('mailWithMarker_GEventEvaluator');">View as .groovy</span> <pre id="mailWithMarker_GEventEvaluator" class="prettyprint source"><configuration> <appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender"> <evaluator class="ch.qos.logback.classic.boolex.GEventEvaluator"> <expression> e.marker?.contains("NOTIFY_ADMIN") || e.marker?.contains("TRANSACTION_FAILURE") </expression> </evaluator> ... same as above </appender> </configuration></pre> <p>Note that since the event may lack a marker, the value of e.marker can be null. Hence the use of Groovy's <a href="http://groovy.codehaus.org/Null+Object+Pattern">safe dereferencing operator</a>, that is the .? operator. </p> <h3><a name="smtpAuthentication" href="#smtpAuthentication"><span class="anchor"/></a>Authentication/STARTTLS/SSL</h3> <p><code>SMTPAppender</code> supports authentication via plain user passwords as well as both the STARTTLS and SSL protocols. Note that STARTTLS differs from SSL in that, in STARTTLS, the connection is initially non-encrypted and only after the STARTTLS command is issued by the client (if the server supports it) does the connection switch to SSL. In SSL mode, the connection is encrypted right from the start. </p> <h3><a name="gmailSSL" href="#gmailSSL"><span class="anchor"/></a>SMTPAppender configuration for Gmail (SSL)</h3> <p>The next example shows you how to configure <code>SMTPAppender</code> for Gmail with the SSL protocol. </p> <p class="example">Example:: <code>SMTPAppender</code> to Gmail using SSL (logback-examples/src/main/java/chapters/appenders/mail/gmailSSL.xml)</p> <span class="asGroovy" onclick="return asGroovy('gmailSSLExample');">View as .groovy</span> <pre id="gmailSSLExample" class="prettyprint source"><configuration> <appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender"> <b><smtpHost>smtp.gmail.com</smtpHost></b> <b><smtpPort>465</smtpPort></b> <b><SSL>true</SSL></b> <b><username>YOUR_USERNAME@gmail.com</username></b> <b><password>YOUR_GMAIL_PASSWORD</password></b> <to>EMAIL-DESTINATION</to> <to>ANOTHER_EMAIL_DESTINATION</to> <!-- additional destinations are possible --> <from>YOUR_USERNAME@gmail.com</from> <subject>TESTING: %logger{20} - %m</subject> <layout class="ch.qos.logback.classic.PatternLayout"> <pattern>%date %-5level %logger{35} - %message%n</pattern> </layout> </appender> <root level="DEBUG"> <appender-ref ref="EMAIL" /> </root> </configuration></pre> <h3><a name="gmailSTARTTLS" href="#gmailSTARTTLS"><span class="anchor"/></a>SMTPAppender for Gmail (STARTTLS)</h3> <p>The next example shows you how to configure <code>SMTPAppender</code> for Gmail for the STARTTLS protocol. </p> <p class="example">Example: <code>SMTPAppender</code> to GMAIL using STARTTLS (logback-examples/src/main/java/chapters/appenders/mail/gmailSTARTTLS.xml)</p> <span class="asGroovy" onclick="return asGroovy('gmailSTARTTLSExample');">View as .groovy</span> <pre id="gmailSTARTTLSExample" class="prettyprint source"><configuration> <appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender"> <smtpHost>smtp.gmail.com</smtpHost> <smtpPort>587</smtpPort> <STARTTLS>true</STARTTLS> <username>YOUR_USERNAME@gmail.com</username> <password>YOUR_GMAIL_xPASSWORD</password> <to>EMAIL-DESTINATION</to> <to>ANOTHER_EMAIL_DESTINATION</to> <!-- additional destinations are possible --> <from>YOUR_USERNAME@gmail.com</from> <subject>TESTING: %logger{20} - %m</subject> <layout class="ch.qos.logback.classic.PatternLayout"> <pattern>%date %-5level %logger - %message%n</pattern> </layout> </appender> <root level="DEBUG"> <appender-ref ref="EMAIL" /> </root> </configuration></pre> <h3><a name="smtpDiscriminator" href="#smtpDiscriminator"><span class="anchor"/></a>SMTPAppender with MDCDiscriminator</h3> <p>As mentioned earlier, by specifying a discriminator other than the default one, <code>SMTPAppender</code> will generate email messages containing events pertaining to a particular user, user session or client IP address, depending on the specified discriminator. </p> <p>The next example illustrates the use of <a href="../xref/ch/qos/logback/classic/sift/MDCBasedDiscriminator.html">MDCBasedDiscriminator</a> in conjunction with the MDC key named "req.remoteHost", assumed to contain the IP address of the remote host accessing a fictitious application. In a web-application, you could use <a href="mdc.html#mis">MDCInsertingServletFilter</a> to populate MDC values. </p> <p class="example">Example: <code>SMTPAppender</code> with MDCBasedDsicriminator (logback-examples/src/main/java/chapters/appenders/mail/mailWithMDCBasedDiscriminator.xml)</p> <span class="asGroovy" onclick="return asGroovy('mailWithMDCBasedDiscriminator');">View as .groovy</span> <pre id="mailWithMDCBasedDiscriminator" class="prettyprint source"><configuration> <appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender"> <smtpHost>ADDRESS-OF-YOUR-SMTP-HOST</smtpHost> <to>EMAIL-DESTINATION</to> <from>SENDER-EMAIL</from> <b><discriminator class="ch.qos.logback.classic.sift.MDCBasedDiscriminator"></b> <b><key>req.remoteHost</key></b> <b><defaultValue>default</defaultValue></b> <b></discriminator></b> <subject>${HOSTNAME} -- %X{req.remoteHost} %msg"</subject> <layout class="ch.qos.logback.classic.html.HTMLLayout"> <pattern>%date%level%thread%X{req.remoteHost}%X{req.requestURL}%logger%msg</pattern> </layout> </appender> <root> <level level="DEBUG"/> <appender-ref ref="EMAIL" /> </root> </configuration></pre> <p>Thus, each outgoing email generated by <code>SMTPAppender</code> will belong to a <em>unique</em> remote host, greatly facilitating problem diagnosis. </p> <h4><a name= "bufferManagement" href="#bufferManagement"><span class="anchor"/></a>Buffer management in very busy systems</h4> <p>Internally, each distinct value returned by the discriminator will cause the creation of a new cyclic buffer. However, at most <span class="prop">maxNumberOfBuffers</span> (by default 64) will be maintained. Whenever the number of buffers rises above <span class="prop">maxNumberOfBuffers</span>, the least recently updated buffer is automatically discarded. As a second safety measure, any buffer which has not been updated in the last 30 minutes will be automatically discarded as well.</p> <p>On systems serving a large number of transactions per minute, allowing only a small number for <span class="prop">maxNumberOfBuffers</span> (by default 64) will often cause the number of events in the outgoing email to be unnecessarily small. Indeed, in the presence of a large number of transactions, there will be more than one buffer associated with the same transaction as buffers will be killed and re-born in succession for the same discriminator value (or transaction). Note that in even such very busy systems, the maximum number of cyclic buffers is capped by <span class="prop">maxNumberOfBuffers</span>. </p> <p>To avoid such yo-yo effects, <code>SMTPAppender</code> will release the buffer associated with a given discriminator key as soon as it sees an event marked as "FINALIZE_SESSION". This will cause the appropriate buffer to be discarded at the end of each transaction. You can then safely increase the value of <span class="prop">maxNumberOfBuffers</span> to a larger value such as 512 or 1024 without risking running out of memory. </p> <p>There are three distinct but complementary mechanisms working together to manage cyclic buffers. They ensure that only relevant buffers are kept alive at any given moment, even in very busy systems.</p> <!-- =========================================================== --> <!-- =========================================================== --> <h3><a name="DBAppender" href="#DBAppender"><span class="anchor"/></a>DBAppender </h3> <p>The <a href="../xref/ch/qos/logback/classic/db/DBAppender.html"><code>DBAppender</code></a> inserts logging events into three database tables in a format independent of the Java programming language. </p> <p>These three tables are <em>logging_event</em>, <em>logging_event_property</em> and <em>logging_event_exception</em>. They must exist before <code>DBAppender</code> can be used. Logback ships with SQL scripts that will create the tables. They can be found under the <em>logback-classic/src/main/java/ch/qos/logback/classic/db/script</em> folder. There is a specific script for each of the most popular database systems. If the script for your particular type of database system is missing, it should be quite easy to write one, taking example on the already existing scripts. If you send them to us, we will gladly include missing scripts in future releases. </p> <p>If your JDBC driver supports the <code>getGeneratedKeys</code> method introduced in JDBC 3.0 specification, assuming you have created the appropriate database tables as mentioned above, then no additional steps are required. Otherwise, there must be an <code>SQLDialect</code> appropriate for your database system. Currently, logback has dialects for H2, HSQL, MS SQL Server, MySQL, Oracle, PostgreSQL, SQLLite and Sybase. </p> <p>The table below summarizes the database types and their support of the <code>getGeneratedKeys()</code> method. </p> <table class="bodyTable striped" border="0" cellpadding="4"> <tr> <th>RDBMS</th> <th>tested version(s) </th> <th>tested JDBC driver version(s) </th> <th> supports <br /> <code>getGeneratedKeys()</code> method </th> <th>is a dialect <br/>provided by logback</th> </tr> <tr> <td>DB2</td> <td>untested</td> <td>untested</td> <td>unknown</td> <td>NO</td> </tr> <tr> <td>H2</td> <td>1.2.132</td> <td>-</td> <td>unknown</td> <td>YES</td> </tr> <tr> <td>HSQL</td> <td>1.8.0.7</td> <td>-</td> <td>NO </td> <td>YES</td> </tr> <tr> <td>Microsoft SQL Server</td> <td>2005</td> <td>2.0.1008.2 (sqljdbc.jar)</td> <td>YES</td> <td>YES</td> </tr> <tr> <td>MySQL</td> <td>5.0.22</td> <td>5.0.8 (mysql-connector.jar)</td> <td>YES</td> <td>YES</td> </tr> <tr> <td>PostgreSQL</td> <td>8.x</td> <td>8.4-701.jdbc4</td> <td>NO</td> <td>YES</td> </tr> <tr> <td>Oracle</td> <td>10g</td> <td>10.2.0.1 (ojdbc14.jar)</td> <td>YES</td> <td>YES</td> </tr> <tr> <td>SQLLite</td> <td>3.7.4</td> <td>-</td> <td>unknown</td> <td>YES</td> </tr> <tr> <td>Sybase SQLAnywhere</td> <td>10.0.1</td> <td>-</td> <td>unknown</td> <td>YES</td> </tr> </table> <p>Experiments show that writing a single event into the database takes approximately 10 milliseconds, on a "standard" PC. If pooled connections are used, this figure drops to around 1 millisecond. Note that most JDBC drivers already ship with connection pooling support. </p> <p>Configuring logback to use <code>DBAppender</code> can be done in several different ways, depending on the tools one has to connect to the database, and the database itself. The key issue in configuring <code>DBAppender</code> is about setting its <code>ConnectionSource</code> object, as we shall discover shortly. </p> <p>Once <code>DBAppender</code> is configured for your database, logging events are sent to the specified database. As stated previously, there are three tables used by logback to store logging event data. </p> <p> The <em>logging_event</em> table contains the following fields: </p> <table class="bodyTable striped"> <tr> <th>Field</th> <th>Type</th> <th>Description</th> </tr> <tr> <td><b>timestamp</b></td> <td><code>big int</code></td> <td>The timestamp that was valid at the logging event's creation.</td> </tr> <tr> <td><b>formatted_message</b></td> <td><code>text</code></td> <td>The message that has been added to the logging event, after formatting with <code>org.slf4j.impl.MessageFormatter</code>, in case objects were passed along with the message.</td> </tr> <tr> <td><b>logger_name</b></td> <td><code>varchar</code></td> <td>The name of the logger used to issue the logging request.</td> </tr> <tr> <td><b>level_string</b></td> <td><code>varchar</code></td> <td>The level of the logging event.</td> </tr> <tr> <td><b>reference_flag</b></td> <td><code>smallint</code></td> <td> <p>This field is used by logback to identify logging events that have an exception or <code>MDC</code>property values associated. </p> <p>Its value is computed by <code>ch.qos.logback.classic.db.DBHelper</code>. A logging event that contains <code>MDC</code> or <code>Context</code> properties has a flag number of <em>1</em>. One that contains an exception has a flag number of <em>2</em>. A logging event that contains both elements has a flag number of <em>3</em>. </p> </td> </tr> <tr> <td><b>caller_filename</b></td> <td><code>varchar</code></td> <td>The name of the file where the logging request was issued.</td> </tr> <tr> <td><b>caller_class</b></td> <td><code>varchar</code></td> <td>The class where the logging request was issued.</td> </tr> <tr> <td><b>caller_method</b></td> <td><code>varchar</code></td> <td>The name of the method where the logging request was issued.</td> </tr> <tr> <td><b>caller_line</b></td> <td><code>char</code></td> <td>The line number where the logging request was issued.</td> </tr> <tr> <td><b>event_id</b></td> <td><code>int</code></td> <td>The database id of the logging event.</td> </tr> </table> <p> The <em>logging_event_property</em> is used to store the keys and values contained in the <code>MDC</code> or the <code>Context</code>. It contains these fields: </p> <table class="bodyTable striped"> <tr> <th>Field</th> <th>Type</th> <th>Description</th> </tr> <tr> <td><b>event_id</b></td> <td><code>int</code></td> <td>The database id of the logging event.</td> </tr> <tr> <td><b>mapped_key</b></td> <td><code>varchar</code></td> <td>The key of the <code>MDC</code> property</td> </tr> <tr> <td><b>mapped_value</b></td> <td><code>text</code></td> <td>The value of the <code>MDC</code> property</td> </tr> </table> <p> The <em>logging_event_exception</em> table contains the following fields: </p> <table class="bodyTable striped"> <tr> <th>Field</th> <th>Type</th> <th>Description</th> </tr> <tr> <td><b>event_id</b></td> <td><code>int</code></td> <td>The database id of the logging event.</td> </tr> <tr> <td><b>i</b></td> <td><code>smallint</code></td> <td>The index of the line in the full stack trace.</td> </tr> <tr> <td><b>trace_line</b></td> <td><code>varchar</code></td> <td>The corresponding line</td> </tr> </table> <p> To give a more visual example of the work done by <code>DBAppender</code>, here is a screenshot of a MySQL database with content provided by <code>DBAppender</code>. </p> <p>The <em>logging_event</em> table:</p> <img src="images/chapters/appenders/dbAppenderLE.gif" alt="Logging Event table" /> <p>The <em>logging_event_exception</em> table:</p> <img src="images/chapters/appenders/dbAppenderLEException.gif" alt="Logging Event Exception table" /> <p>The <em>logging_event_property</em> table:</p> <img src="images/chapters/appenders/dbAppenderLEProperty.gif" alt="Logging Event Property table" /> <h4>ConnectionSource</h4> <p>The <code>ConnectionSource</code> interface provides a pluggable means of transparently obtaining JDBC connections for logback classes that require the use of a <code>java.sql.Connection</code>. There are currently three implementations of <code>ConnectionSource</code>, namely <code>DataSourceConnectionSource</code>, <code>DriverManagerConnectionSource</code> and <code>JNDIConnectionSource</code>. </p> <p> The first example that we will review is a configuration using <code>DriverManagerConnectionSource</code> and a MySQL database. The following configuration file is what one would need. </p> <p class="example">Example: <code>DBAppender</code> configuration (logback-examples/src/main/java/chapters/appenders/db/append-toMySQL-with-driverManager.xml)</p> <span class="asGroovy" onclick="return asGroovy('append-toMySQL-with-driverManager');">View as .groovy</span> <pre id="append-toMySQL-with-driverManager" class="prettyprint source"><configuration> <b><appender name="DB" class="ch.qos.logback.classic.db.DBAppender"> <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource"> <driverClass>com.mysql.jdbc.Driver</driverClass> <url>jdbc:mysql://host_name:3306/datebase_name</url> <user>username</user> <password>password</password> </connectionSource> </appender></b> <root level="DEBUG" > <appender-ref ref="DB" /> </root> </configuration></pre> <p> The correct driver must be declared. Here, the <code>com.mysql.jdbc.Driver</code> class is used. The <span class="prop">url</span> must begin with <em>jdbc:myslq://</em>. </p> <p> The <a href="../xref/ch/qos/logback/core/db/DriverManagerConnectionSource.html"> <code>DriverManagerConnectionSource</code></a> is an implementation of <code>ConnectionSource</code> that obtains the connection in the traditional JDBC manner based on the connection URL. </p> <p> Note that this class will establish a new <code>Connection</code> for each call to <code>getConnection()</code>. It is recommended that you either use a JDBC driver that natively supports connection pooling or that you create your own implementation of <code>ConnectionSource</code> that taps into whatever pooling mechanism you are already using. If you have access to a JNDI implementation that supports <code>javax.sql.DataSource</code>, e.g. within a J2EE application server, see <a href="#JNDIConnectionSource"><code>JNDIConnectionSource</code></a> below. </p> <!-- HAS TO BE TESTED <p> If you do not have another connection pooling mechanism built into your application, you can use the <a href="http://jakarta.apache.org/commons/dbcp/index.html"> commons-dbcp </a> package from Apache: </p> <pre class="prettyprint source"> <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource"> <param name="driver" value="org.apache.commons.dbcp.PoolingDriver"/> <param name="url" value="jdbc:apache:commons:dbcp:/myPoolingDriver"/> </connectionSource> </pre> <p> Then the configuration information for the commons-dbcp package goes into the file <em>myPoolingDriver.jocl</em> and is placed in the classpath. See the <a href="http://jakarta.apache.org/commons/dbcp/index.html"> commons-dbcp </a> documentation for details. </p> --> <p>Connecting to a database using a <code>DataSource</code> is rather similar. The configuration now uses <a href="../xref/ch/qos/logback/core/db/DataSourceConnectionSource.html"> <code>DataSourceConnectionSource</code></a>, which is an implementation of <code>ConnectionSource</code> that obtains the <code>Connection</code> in the recommended JDBC manner based on a <code>javax.sql.DataSource</code>. </p> <p class="example">Example: <code>DBAppender</code> configuration (logback-examples/src/main/java/chapters/appenders/db/append-with-datasource.xml)</p> <span class="asGroovy" onclick="return asGroovy('append-with-datasource');">View as .groovy</span> <pre id="append-with-datasource" class="prettyprint source"><configuration debug="true"> <appender name="DB" class="ch.qos.logback.classic.db.DBAppender"> <b><connectionSource class="ch.qos.logback.core.db.DataSourceConnectionSource"> <dataSource class="${dataSourceClass}"> </b><!-- Joran cannot substitute variables that are not attribute values. Therefore, we cannot declare the next parameter like the others. --> <b><param name="${url-key:-url}" value="${url_value}"/> <serverName>${serverName}</serverName> <databaseName>${databaseName}</databaseName> </dataSource></b> <user>${user}</user> <password>${password}</password> </connectionSource> </appender> <root level="INFO"> <appender-ref ref="DB" /> </root> </configuration></pre> <p>Note that in this configuration sample, we make heavy use of substitution variables. They are sometimes handy when connection details have to be centralized in a single configuration file and shared by logback and other frameworks. </p> <!-- TO BE TESTED <p>The connection created by <code>DataSourceConnectionSource</code> can be placed in a JNDI context by using <code>BindDataSourceToJNDIAction</code>. In that case, one has to specify the use of this class by adding a new rule to Joran, logback's configuration framework. Here is an excerpt of such a configuration file. </p> <div class="source"><pre><configuration> .. <b><newRule pattern="configuration/bindDataSourceToJNDI" actionClass="ch.qos.logback.core.db.BindDataSourceToJNDIAction"/> <bindDataSourceToJNDI /></b> .. </configuration></pre></div> <p> The <em>newRule</em> element teaches Joran to use specified action class with the given pattern. Then, we simply declare the given element. The action class will be called and our connection source will be bound to a JNDI context. </p> <p>This is a very powerful capability of Joran. If you'd like to read more about Joran, please see the <a href="onJoran.html">chapter to Joran</a>. </p> --> <h4><a name="JNDIConnectionSource" href="#JNDIConnectionSource"><span class="anchor"/></a>JNDIConnectionSource</h4> <p><a href="../xref/ch/qos/logback/core/db/JNDIConnectionSource.html"> <code>JNDIConnectionSource</code></a> is another <code>ConnectionSource</code> implementation shipping in logback. As its name indicates, it retrieves a <code>javax.sql.DataSource</code> from a JNDI and then leverages it to obtain a <code>java.sql.Connection</code> instance. <code>JNDIConnectionSource</code> is primarily designed to be used inside J2EE application servers or by application server clients, assuming the application server supports remote access of <code>javax.sql.DataSource</code>. Thus, one can take advantage of connection pooling and whatever other goodies the application server provides. More importantly, your application will be <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">dryer</a> as it will be no longer necessary to define a <code>DataSource</code> in <em>logback.xml</em>.</p> <p>For example, here is a configuration snippet for Tomcat. It assumes PostgreSQL as the database although any of the supported database systems (listed above) would work.</p> <pre class="prettyprint source"><Context docBase="/path/to/app.war" path="/myapp"> ... <Resource <b>name="jdbc/logging"</b> auth="Container" type="javax.sql.DataSource" username="..." password="..." driverClassName="org.postgresql.Driver" url="jdbc:postgresql://localhost/..." maxActive="8" maxIdle="4"/> ... </Context></pre> <p>Once a <code>DataSource</code> is defined in the J2EE server, it can be easily referenced by your logback configuration file, as shown in the next example.</p> <p class="example">Example: <code>DBAppender</code> configuration by <code>JNDIConnectionSource</code> (logback-examples/src/main/java/chapters/appenders/db/append-via-jndi.xml)</p> <span class="asGroovy" onclick="return asGroovy('append-via-jndi');">View as .groovy</span> <pre id="append-via-jndi" class="prettyprint source"><configuration debug="true"> <appender name="DB" class="ch.qos.logback.classic.db.DBAppender"> <connectionSource class="ch.qos.logback.core.db.JNDIConnectionSource"> <b><!-- please note the "java:comp/env/" prefix --></b> <b><jndiLocation>java:comp/env/jdbc/logging</jndiLocation></b> </connectionSource> </appender> <root level="INFO"> <appender-ref ref="DB" /> </root> </configuration></pre> <p> Note that this class will obtain an <code>javax.naming.InitialContext</code> using the no-argument constructor. This will usually work when executing within a J2EE environment. When outside the J2EE environment, make sure that you provide a <em>jndi.properties</em> file as described by your JNDI provider's documentation. </p> <h4 class="doAnchor">Connection pooling</h4> <p>Logging events can be created at a rather fast pace. To keep up with the flow of events that must be inserted into a database, it is recommended to use connection pooling with <code>DBAppender</code>. </p> <p> Experiment shows that using connection pooling with <code>DBAppender</code> gives a big performance boost. With the following configuration file, logging events are sent to a MySQL database, without any pooling. </p> <p class="example">Example: <code>DBAppender</code> configuration without pooling (logback-examples/src/main/java/chapters/appenders/db/append-toMySQL-with-datasource.xml)</p> <span class="asGroovy" onclick="return asGroovy('append-toMySQL-with-datasource');">View as .groovy</span> <pre id="append-toMySQL-with-datasource" class="prettyprint source"><configuration> <appender name="DB" class="ch.qos.logback.classic.db.DBAppender"> <connectionSource class="ch.qos.logback.core.db.DataSourceConnectionSource"> <dataSource class="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"> <serverName>${serverName}</serverName> <port>${port$</port> <databaseName>${dbName}</databaseName> <user>${user}</user> <password>${pass}</password> </dataSource> </connectionSource> </appender> <root level="DEBUG"> <appender-ref ref="DB" /> </root> </configuration></pre> <p>With this configuration file, sending 500 logging events to a MySQL database takes a whopping 5 seconds, that is 10 milliseconds per request. This figure is unacceptable when dealing with large applications. </p> <p>A dedicated external library is necessary to use connection pooling with <code>DBAppender</code>. The next example uses <a href="http://sourceforge.net/projects/c3p0">c3p0</a>. To be able to use c3p0, one must download it and place <em>c3p0-VERSION.jar</em> in the classpath. </p> <p class="example">Example: <code>DBAppender</code> configuration with pooling (logback-examples/src/main/java/chapters/appenders/db/append-toMySQL-with-datasource-and-pooling.xml)</p> <span class="asGroovy" onclick="return asGroovy('append-toMySQL-with-datasource-and-pooling');">View as .groovy</span> <pre id="append-toMySQL-with-datasource-and-pooling" class="prettyprint source"><configuration> <appender name="DB" class="ch.qos.logback.classic.db.DBAppender"> <connectionSource class="ch.qos.logback.core.db.DataSourceConnectionSource"> <b><dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource"> <driverClass>com.mysql.jdbc.Driver</driverClass> <jdbcUrl>jdbc:mysql://${serverName}:${port}/${dbName}</jdbcUrl> <user>${user}</user> <password>${password}</password> </dataSource></b> </connectionSource> </appender> <root level="DEBUG"> <appender-ref ref="DB" /> </root> </configuration></pre> <p>With this new configuration, sending 500 logging requests to the aforementioned MySQL database takes around 0.5 seconds, for an average of 1 millisecond per request, that is a tenfold improvement in performance. </p> <h3 class="doAnchor" name="SyslogAppender">SyslogAppender</h3> <p>The syslog protocol is a very simple protocol: a syslog sender sends a small message to a syslog receiver. The receiver is commonly called <em>syslog daemon</em> or <em>syslog server</em>. Logback can send messages to a remote syslog daemon. This is achieved by using <a href="../xref/ch/qos/logback/classic/net/SyslogAppender.html"><code>SyslogAppender</code></a>. </p> <p>Here are the properties you can pass to a SyslogAppender.</p> <table class="bodyTable striped"> <tr> <th>Property Name</th> <th>Type</th> <th>Description</th> </tr> <tr> <td><span class="prop" container="syslog">syslogHost</span></td> <td><code>String</code></td> <td>The host name of the syslog server.</td> </tr> <tr> <td><span class="prop" container="syslog">port</span></td> <td><code>String</code></td> <td>The port number on the syslog server to connect to. Normally, one would not want to change the default value of <em>514</em>. </td> </tr> <tr> <td><span class="prop" container="syslog">facility</span></td> <td><code>String</code></td> <td> <p>The <span class="prop">facility</span> is meant to identify the source of a message.</p> <p>The <span class="prop">facility</span> option must be set to one of the strings <em>KERN, USER, MAIL, DAEMON, AUTH, SYSLOG, LPR, NEWS, UUCP, CRON, AUTHPRIV, FTP, NTP, AUDIT, ALERT, CLOCK, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7</em>. Case is not important.</p> </td> </tr> <tr> <td><span class="prop" container="syslog">suffixPattern</span></td> <td><code>String</code></td> <td><p>The <span class="prop">suffixPattern</span> option specifies the format of the non-standardized part of the message sent to the syslog server. By default, its value is <em>[%thread] %logger %msg</em>. Any value that a <code>PatternLayout</code> could use is a correct <span class="prop">suffixPattern</span> value. </p> </td> </tr> <tr> <td><span class="prop" container="syslog">stackTracePattern</span></td> <td><code>String</code></td> <td><p>The <span class="prop">stackTracePattern</span> property allows the customization of the string appearing just before each stack trace line. The default value for this property is "\t", i.e. the tab character. Any value accepted by <code>PatternLayout</code> is a valid value for <span class="prop">stackTracePattern</span>.</p> </td> </tr> <tr> <td><span class="prop" container="syslog">throwableExcluded</span></td> <td><code>boolean</code></td> <td>Setting <span class="prop">throwableExcluded</span> to <code>true</code> will cause stack trace data associated with a Throwable to be omitted. By default, <span class="prop">throwableExcluded</span> is set to <code>false</code> so that stack trace data is sent to the syslog server. </td> </tr> </table> <p>The syslog severity of a logging event is converted from the level of the logging event. The <em>DEBUG</em> level is converted to <em>7</em>, <em>INFO</em> is converted to <em>6</em>, <em>WARN</em> is converted to <em>4</em> and <em>ERROR</em> is converted to <em>3</em>. </p> <p>Since the format of a syslog request follows rather strict rules, there is no layout to be used with <code>SyslogAppender</code>. However, using the <span class="prop">suffixPattern</span> option lets the user display whatever information she wishes. </p> <p>Here is a sample configuration using a <code>SyslogAppender</code>.</p> <p class="example">Example: <code>SyslogAppender</code> configuration (logback-examples/src/main/java/chapters/appenders/conf/logback-syslog.xml)</p> <span class="asGroovy" onclick="return asGroovy('logback-syslog');">View as .groovy</span> <pre id="logback-syslog" class="prettyprint source"><configuration> <appender name="SYSLOG" class="ch.qos.logback.classic.net.SyslogAppender"> <syslogHost>remote_home</syslogHost> <facility>AUTH</facility> <suffixPattern>[%thread] %logger %msg</suffixPattern> </appender> <root level="DEBUG"> <appender-ref ref="SYSLOG" /> </root> </configuration></pre> <p>When testing this configuration, you should verify that the remote syslog daemon accepts requests from an external source. Experience shows that, by default, syslog daemons usually deny requests coming via a network connection. </p> <h3 class="doAnchor" name="SiftingAppender">SiftingAppender</h3> <p>As its name implies, a <code>SiftingAppender</code> can be used to separate (or sift) logging according to a given runtime attribute. For example, <code>SiftingAppender</code> can separate logging events according to user sessions, so that the logs generated by different users go into distinct log files, one log file per user. </p> <p><code>SiftingAppender</code> achieves this feat by creating child appenders on the fly. Child appenders are created based on a template specified within the configuration of the <code>SiftingAppender</code> itself (enclosed within the <code><sift></code> element, see example below). <code>SiftingAppender</code> is responsible for managing the lifecycle of child appenders. For example, <code>SiftingAppender</code> will automatically close and remove any unused child appender. </p> <p>When handling a logging event, <code>SiftingAppender</code> will select a child appender to delegate to. The selection criteria are computed at runtime by a discriminator. The user can specify the selection criteria with the help of a <code><a href="../xref/ch/qos/logback/core/sift/Discriminator.html">Discriminator</a></code>. Let us now study an eaxample. </p> <h4>Example</h4> <p>The <a href="../xref/chapters/appenders/sift/SiftExample.html">SiftExample</a> application logs a message stating that the application has started. It then sets the MDC key "userid" to "Alice" and logs a message. Here is the salient code:</p> <p class="source">logger.debug("Application started"); MDC.put("userid", "Alice"); logger.debug("Alice says hello"); </p> <p>The template for the configuration file illustrates the use of <code>SiftingAppender</code>.</p> <p class="example">Example: <code>SiftingAppender</code> configuration (logback-examples/src/main/java/chapters/appenders/sift/byUserid.xml)</p> <span class="asGroovy" onclick="return asGroovy('byUserid');">View as .groovy</span> <pre id="byUserid" class="prettyprint source"><configuration> <b><appender name="SIFT" class="ch.qos.logback.classic.sift.SiftingAppender"></b> <!-- in the absence of the class attribute, it is assumed that the desired discriminator type is ch.qos.logback.classic.sift.MDCBasedDiscriminator --> <b><discriminator></b> <b><key><span class="green">userid</span></key></b> <b><defaultValue>unknown</defaultValue></b> <b></discriminator></b> <b><sift></b> <b><appender name="FILE-<span class="green">${userid}</span>" class="ch.qos.logback.core.FileAppender"></b> <b><file><span class="green">${userid}</span>.log</file></b> <b><append>false</append></b> <b><layout class="ch.qos.logback.classic.PatternLayout"></b> <b><pattern>%d [%thread] %level %mdc %logger{35} - %msg%n</pattern></b> <b></layout></b> <b></appender></b> <b></sift></b> </appender> <root level="DEBUG"> <appender-ref ref="SIFT" /> </root> </configuration></pre> <p>In the absence of a class attribute, it is assumed that the discriminator type is <a href="../xref/ch/qos/logback/classic/sift/MDCBasedDiscriminator.html">MDCBasedDiscriminator</a>. The discrimating value is the MDC value associated with the key given by the <span class="prop">key</span> property. However, if that MDC value is null, then <span class="prop">defaultValue</span> is used as the discrimating value. </p> <p>The <code>SiftingAppender</code> is unique in its capacity to reference and configure child appenders. In the above example, <code>SiftingAppender</code> will create multiple <code>FileAppender</code> instances, each <code>FileAppender</code> instance identified by the value associated with the "userid" MDC key. Whenever the "userid" MDC key is assigned a new value, a new <code>FileAppender</code> instance will be built from scratch. The <code>SiftingAppender</code> keeps track of the appenders it creates. Appenders unused for 30 minutes will be automatically closed and discarded. </p> <p><span class="label notice">Variable export</span> It is not enough to have different appender instances; each instance must output to a distinct target resource. To allow such differentiation, within the appender template, the key passed to the discriminator, "userid" in the above example, is exported and becomes a <a href="configuration.html#variableSubstitution">variable</a>. Consequently, this variable can be used to differentiate the actual resource used by a given child appender. </p> <p>Running the <code>SiftExample</code> application with the "byUserid.xml" configuration file shown above, will result in two distinct log files, "unknown.log" and "Alice.log". </p> <h3><a name="AsyncAppender" href="#AsyncAppender">AsyncAppender</a></h3> <p>AsyncAppender logs <a href="../apidocs/ch/qos/logback/classic/spi/ILoggingEvent.html">ILoggingEvent</a>s asynchronously. It acts solely as an event dispatcher and must therefore reference another appender in order to do anything useful. In order to avoid loss of logging events, this appender should be closed. It is the user's responsibility to close appenders, typically at the end of the application lifecycle. </p> <p><span class="label notice">Lossy by default if 80% full</span> AsyncAppender buffers events in a <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html"> BlockingQueue</a>. A worker thread created by <code>AsyncAppender</code> takes events from the head of the queue, and dispatches them to the single appender attached to <code>AsyncAppender</code>. Note that by default, <code>AsyncAppender</code> will drop events of level TRACE, DEBUG and INFO if its queue is 80% full. This strategy has an amazingly favorable effect on performance at the cost of event loss. </p> <p>Here is the list of properties admitted by <code>AsyncAppender:</code></p> <table class="bodyTable striped"> <tr> <th>Property Name</th> <th>Type</th> <th>Description</th> </tr> <tr> <td><span class="prop" container="async">queueSize</span></td> <td><code>int</code></td> <td>The maximum capacity of the blocking queue. By default, <span class="prop">queueSize</span> is set to 256. </td> </tr> <tr> <td><span class="prop" container="async">discardingThreshold</span></td> <td><code>int</code></td> <td>By default, when the blocking queue has 20% capacity remaining, it will drop events of level TRACE, DEBUG and INFO, keeping only events of level WARN and ERROR. To keep all events, set <span class="prop">discardingThreshold</span> to 0. </td> </tr> <tr> <td><span class="prop" container="async">includeCallerData</span></td> <td><code>boolean</code></td> <td>Extracting caller data can be rather expensive. To improve performance, by default, caller data associated with an event is not extracted when the event added to the event queue. By default, only "cheap" data like the thread name and the <a href="mdc.html">MDC</a> are copied. You can direct this appender to include caller data by setting the <span class="prop">includeCallerData</span> property to true. </td> </tr> </table> <p>By default, event queue is configured with a maximum capacity of 256 events. If the queue is filled up, then application threads are blocked from logging new events until the worker thread has had a chance to dispatch one or more events. When the queue is no longer at its maximum capacity, application threads are able to start logging events once again. Asynchronous logging therefore becomes pseudo-synchronous when the appender is operating at or near the capacity of its event buffer. This is not necessarily a bad thing. The appender is designed to allow the application to keep on running, albeit taking slightly more time to log events until the pressure on the appenders buffer eases. </p> <p>Optimally tuning the size of the appenders event queue for maximum application throughput depends upon several factors. Any or all of the following factors are likely to cause pseudo-synchronous behavior to be exhibited:</p> <ul> <li>Large numbers of application threads</li> <li>Large numbers of logging events per application call</li> <li>Large amounts of data per logging event</li> <li>High latency of child appenders</li> </ul> <p>To keep things moving, increasing the size of the queue will generally help, at the expense of heap available to the application. </p> <p><span class="label notice">Lossy behavior</span> In light of the discussion above and in order to reduce blocking, by default, when less than 20% of the queue capacilty remains, <code>AsyncAppender</code> will drop events of level TRACE, DEBUG and INFO keeping only events of level WARN and ERROR. This strategy ensures non-blocking handling of logging events (hence excellent performance) at the cost loosing events of level TRACE, DEBUG and INFO when the queue has less than 20% capacity. Event loss can be prevented by setting the <span class="prop">discardingThreshold</span> property to 0 (zero). </p> <p class="example">Example: <code>AsyncAppender</code> configuration (logback-examples/src/main/java/chapters/appenders/conc/logback-async.xml)</p> <span class="asGroovy" onclick="return asGroovy('asyncAppender');">View as .groovy</span> <pre id="asyncAppender" class="prettyprint source"><configuration> <appender name="<b>FILE</b>" class="ch.qos.logback.core.FileAppender"> <file>myapp.log</file> <encoder> <pattern>%logger{35} - %msg%n</pattern> </encoder> </appender> <b><appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender"></b> <b><appender-ref ref="FILE" /></b> <b></appender></b> <root level="DEBUG"> <appender-ref ref="<b>ASYNC</b>" /> </root> </configuration></pre> <h3><a name="WriteYourOwnAppender" href="#WriteYourOwnAppender">Writing your own Appender</a></h3> <p>You can easily write your appender by subclassing <code>AppenderBase</code>. It handles support for filters, status messages and other functionality shared by most appenders. The derived class only needs to implement one method, namely <code>append(Object eventObject)</code>. </p> <p>The <code>CountingConsoleAppender</code>, which we list next, appends a limited number of incoming events on the console. It shuts down after the limit is reached. It uses a <code>Layout</code> to format the events and accepts a parameter. Thus, a few more methods are needed. </p> <em>Example 4.<span class="autoExec"/>: <code>CountingConsoleAppender</code> (logback-examples/src/main/java/chapters/appenders/CountingConsoleAppender.java)</em> <pre class="prettyprint source">package chapters.appenders; import ch.qos.logback.core.AppenderBase; import ch.qos.logback.core.Layout; public class CountingConsoleAppender extends AppenderBase<ILoggingEvent> { static int DEFAULT_LIMIT = 16; int counter = 0; int limit = DEFAULT_LIMIT; public CountingConsoleAppender() { } public void setLimit(int limit) { this.limit = limit; } public int getLimit() { return limit; } @Override public void start() { if (this.layout == null) { addError("No layout set for the appender named ["+ name +"]."); return; } super.start(); } public void append(ILoggingEvent event) { if (counter >= limit) { return; } // output the events as formatted by our layout System.out.print(this.layout.doLayout(event)); // prepare for next event counter++; } }</pre> <p>The <code>start()</code> method checks for the presence of a <code>Layout</code>. In case the layout is not set, the appender fails to start with an error message. </p> <p>This custom appender illustrates two points:</p> <ul> <li>All properties that follow the setter/getter JavaBeans conventions are handled transparently. The <code>start()</code> method, which is called automatically during logback configuration, has the responsibility of verifying that the various properties of the appender are coherent. </li> <li>The <code>AppenderBase.doAppend()</code> method invokes the append() method of its derived classes. Actual output operations occur in the <code>append</code>() method. In particular, it is in this method that appenders format events by invoking their layouts. </li> </ul> <p>The <a href="../xref/chapters/appenders/CountingConsoleAppender.html"><code>CountingConsoleAppender</code></a> can be configured like any other appender. See sample configuration file <em>logback-examples/src/main/java/chapters/appenders/countingConsole.xml</em> for an example. </p> <h2><a name="logback_access" href="#logback_access">Logback Access</a></h2> <p>Most of the appenders found in logback-classic have their equivalent in logback-access. These work essentially in the same way as their logback-classic counterparts. In the next section, we will cover their use. </p> <a name="AccessSocketAppender"/> <h3>SocketAppender</h3> <p>The <a href="../xref/ch/qos/logback/access/net/SocketAppender.html"> <code>SocketAppender</code></a> is designed to log to a remote entity by transmitting serialized <code>AccessEvent</code> objects over the wire. Remote logging is non-intrusive as far as the access event is concerned. On the receiving end after deserialization, the event can be logged as if it were generated locally. </p> <p> The properties of access' <code>SocketAppender</code> are the same as those available for classic's <code>SocketAppender</code>. </p> <a name="AccessSMTPAppender"></a> <h3>SMTPAppender</h3> <p> Access' <a href="../xref/ch/qos/logback/access/net/SMTPAppender.html"> <code>SMTPAppender</code></a> works in the same way as its Classic counterpart. However, the <span class="prop">evaluator</span> option is rather different. By default, a <code>URLEvaluator</code> object is used by <code>SMTPAppender</code>. This evaluator contains a list of URLs that are checked against the current request's URL. When one of the pages given to the <code>URLEvaluator</code> is requested, <code>SMTPAppender</code> sends an email. </p> <p> Here is a sample configuration of a <code>SMTPAppender</code> in the access environment. </p> <p class="example">Example: <code>SMTPAppender</code> configuration (logback-examples/src/main/java/chapters/appenders/conf/access/logback-smtp.xml)</p> <pre class="prettyprint source"><appender name="SMTP" class="ch.qos.logback.access.net.SMTPAppender"> <layout class="ch.qos.logback.access.html.HTMLLayout"> <pattern>%h%l%u%t%r%s%b</pattern> </layout> <b><Evaluator class="ch.qos.logback.access.net.URLEvaluator"> <URL>url1.jsp</URL> <URL>directory/url2.html</URL> </Evaluator></b> <from>sender_email@host.com</from> <smtpHost>mail.domain.com</smtpHost> <to>recipient_email@host.com</to> </appender></pre> <p>This way of triggering the email lets users select pages that are important steps in a specific process, for example. When such a page is accessed, the email is sent with the pages that were accessed previously, and any information the user wants to be included in the email. </p> <a name="AccessDBAppender"></a> <h3>DBAppender</h3> <p> <a href="../xref/ch/qos/logback/access/db/DBAppender.html"><code>DBAppender</code></a> is used to insert the access events into a database. </p> <p>Two tables are used by <code>DBAppender</code>: <em>access_event</em> and <em>access_event_header</em>. They both must exist before <code>DBAppender</code> can be used. Logback ships with SQL scripts that will create the tables. They can be found in the <em>logback-access/src/main/java/ch/qos/logback/access/db/script</em> directory. There is a specific script for each of the most popular database systems. If the script for your particular type of database system is missing, it should be quite easy to write one, taking as example one of the existing scripts. You are encouraged to contribute such missing scripts back to the project. </p> <p>The <em>access_event</em> table's fields are described below:</p> <table class="bodyTable striped"> <tr> <th>Field</th> <th>Type</th> <th>Description</th> </tr> <tr> <td><b>timestamp</b></td> <td><code>big int</code></td> <td>The timestamp that was valid at the access event's creation.</td> </tr> <tr> <td><b>requestURI</b></td> <td><code>varchar</code></td> <td>The URI that was requested.</td> </tr> <tr> <td><b>requestURL</b></td> <td><code>varchar</code></td> <td>The URL that was requested. This is a string composed of the request method, the request URI and the request protocol. </td> </tr> <tr> <td><b>remoteHost</b></td> <td><code>varchar</code></td> <td>The name of the remote host.</td> </tr> <tr> <td><b>remoteUser</b></td> <td><code>varchar</code></td> <td> The name of the remote user. </td> </tr> <tr> <td><b>remoteAddr</b></td> <td><code>varchar</code></td> <td>The remote IP address.</td> </tr> <tr> <td><b>protocol</b></td> <td><code>varchar</code></td> <td>The request protocol, like <em>HTTP</em> or <em>HTTPS</em>.</td> </tr> <tr> <td><b>method</b></td> <td><code>varchar</code></td> <td>The request method, usually <em>GET</em> or <em>POST</em>.</td> </tr> <tr> <td><b>serverName</b></td> <td><code>varchar</code></td> <td>The name of the server that issued the request.</td> </tr> <tr> <td><b>event_id</b></td> <td><code>int</code></td> <td>The database id of the access event.</td> </tr> </table> <p> The <em>access_event_header</em> table contains the header of each request. The information is organised as shown below: </p> <table class="bodyTable striped"> <tr> <th>Field</th> <th>Type</th> <th>Description</th> </tr> <tr> <td><b>event_id</b></td> <td><code>int</code></td> <td>The database id of the corresponding access event.</td> </tr> <tr> <td><b>header_key</b></td> <td><code>varchar</code></td> <td>The header name, for example <em>User-Agent</em>.</td> </tr> <tr> <td><b>header_value</b></td> <td><code>varchar</code></td> <td>The header value, for example <em>Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1) Gecko/20061010 Firefox/2.0</em></td> </tr> </table> <p>All properties of classic's <code>DBAppender</code> are available in access's <code>DBAppender</code>. The latter offers one more option, described below. </p> <table class="bodyTable striped"> <tr> <th>Property Name</th> <th>Type</th> <th>Description</th> </tr> <tr> <td> <b> <span class="prop">insertHeaders</span> </b> </td> <td> <code>boolean</code> </td> <td> Tells the <code>DBAppender</code> to populate the database with the header information of all incoming requests. </td> </tr> </table> <p>Here is a sample configuration that uses <code>DBAppender</code>.</p> <p class="example">Example: DBAppender configuration <em>(logback-examples/src/main/java/chapters/appenders/conf/access/logback-DB.xml)</em></p> <pre class="prettyprint source"><configuration> <appender name="DB" class="ch.qos.logback.access.db.DBAppender"> <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource"> <driverClass>com.mysql.jdbc.Driver</driverClass> <url>jdbc:mysql://localhost:3306/logbackdb</url> <user>logback</user> <password>logback</password> </connectionSource> <insertHeaders>true</insertHeaders> </appender> <appender-ref ref="DB" /> </configuration></pre> <h3><a name="AccessSiftingAppender" href="#AccessSiftingAppender">SiftingAppender</a></h3> <p>The SiftingAppender in logback-access is quite similar to its logback-classic counterpart. The main difference is that in logback-access the default discriminator, namely <a href="../xref/ch/qos/logback/access/sift/AccessEventDiscriminator.html">AccessEventDiscriminator</a>, is not MDC based. As its name suggests, AccessEventDiscriminator, uses a designated field in AccessEvent as the basis for selecting a nested appender. If the value of the designated field is null, then the value specified in the <span class="prop">defaultValue</span> property is used. </p> <p>The designated AccessEvent field can be one of COOKIE, REQUEST_ATTRIBUTE, SESSION_ATTRIBUTE, REMOTE_ADDRESS, LOCAL_PORT, REQUEST_URI. Note that the first three fields require that the <span class="prop">AdditionalKey</span> property also be specified.</p> <p>Below is an example configuration file.</p> <p class="example">Example: SiftingAppender configuration (logback-examples/src/main/java/chapters/appenders/conf/sift/access-siftingFile.xml)</em> <pre class="prettyprint source"><configuration> <appender name="SIFTING" class="ch.qos.logback.access.sift.SiftingAppender"> <Discriminator class="ch.qos.logback.access.sift.AccessEventDiscriminator"> <Key>id</Key> <FieldName>SESSION_ATTRIBUTE</FieldName> <AdditionalKey>username</AdditionalKey> <defaultValue>NA</defaultValue> </Discriminator> <sift> <appender name="ch.qos.logback:logback-site:jar:1.0.9" class="ch.qos.logback.core.FileAppender"> <file>byUser/ch.qos.logback:logback-site:jar:1.0.9.log</file> <layout class="ch.qos.logback.access.PatternLayout"> <pattern>%h %l %u %t \"%r\" %s %b</pattern> </layout> </appender> </sift> </appender> <appender-ref ref="SIFTING" /> </configuration></pre> <p>In the above configuration file, a <code>SiftingAppender</code> nests <code>FileAppender</code> instances. The key "id" is designated as a variable which will be available to the nested <code>FileAppender</code> instances. The default discriminator, namely <code>AccessEventDiscriminator</code>, will search for a "username" session attribute in each <code>AccessEvent</code>. If no such attribute is available, then the default value "NA" will be used. Thus, assuming the session attribute named "username" contains the username of each logged on user, there will be a log file under the <em>byUser/</em> folder (of the current folder) named after each user containing the access logs for that user. </p> <script src="../templates/footer.js" type="text/javascript"></script> </div> </body> </html>