<document>
	<!-- 
		
		Warning: do not use any auto-format function on this file.
		Since "source" divs use pre as white-space, it affects the
		look of the code parts in this document.
		
	-->


	<body>
		<h2>Chapter 5: Layouts</h2>
		<div class="author">
			Authors: Ceki G&#252;lc&#252;, S&#233;bastien Pennec
		</div>


		<table>
			<tr>
				<td valign="top" align="top">
					<a rel="license"
						href="http://creativecommons.org/licenses/by-nc-nd/2.5/">
						<img alt="Creative Commons License" border="0"
							valign="top" align="top"
							src="http://creativecommons.org/images/public/somerights20.png" />
					</a>
				</td>
				<td>
					<p>Copyright &#169; 2000-2006, QOS.ch</p>

					<p>
						This work is licensed under a
						<a rel="license"
							href="http://creativecommons.org/licenses/by-nc-nd/2.5/">
							Creative Commons
							Attribution-Noncommercial-No Derivative
							Works 2.5 License
						</a>
						.
					</p>
				</td>
			</tr>
		</table>

		<h2>What is a layout</h2>

		<p>
			While appenders are responsible for writing logging output
			to an appender dependent device, layouts are responsible for
			the format of the output. In case you were wondering,
			layouts have nothing to do with large estates in Florida.
			The
			<code>format()</code>
			method in the Layout class takes a object that represents
			the logging event and returns a String. A synopsis of the
			Layout interface is shown below.
		</p>
		<div class="source">
			public interface Layout extends ContextAware, LifeCycle {

			String doLayout(Object event);

			String getHeader();

			String getFooter();

			String getContentType();
		</div>
		<p>
			This interface is really simple and yet is sufficent for
			many formatting needs.
		</p>

		<!-- Do we add here something about one's personal implementation of Layout?  -->

		<h2>Logback classic</h2>

		<p>
			As we've seen, a Layout implementation takes as a parameter
			an object that represents a logging event. The typing of the
			parameter to <code>Object</code>
			is because logging events may have different ways of being
			designed. In logback classic, a logging event is represented
			by the <code>ch.qos.logback.classic.LoggingEvent</code>
			class. Therefore, all layouts in logback classic implement a
			sub-interface of <code>Layout</code> named <code>ClassicLayout</code>.
		</p>

		<p>
			Here is what a
			<code>ClassicLayout</code>
			looks like:
		</p>

		<div class="source">
			public interface ClassicLayout extends Layout {

			String doLayout(LoggingEvent event);

			}
		</div>

		<h3>PatternLayout</h3>

		<p>
			Logback ships with a flexible layout called <code>PatternLayout</code>. 
			As all classic layouts, <code>PatternLayout</code>
			takes a logging event and returns a String. However, the
			returned String can be modified at will by tweaking its
			conversion pattern. 
		</p>
		<p>
			The conversion pattern of <code>PatternLayout</code>
			is closely related to the conversion pattern of the
			<code>printf()</code> function in the C programming language. 
			A conversion pattern is composed of literal text and format 
			control expressions called conversion specifiers. 
			You are free to insert any literal text within the conversion pattern. 
			Each conversion specifier starts with a percent sign (%) and is followed by
			optional format modifiers and a conversion character. The
			conversion character controls the type of data to use, e.g.
			logger name, level, date, thread name. The format modifiers
			control such things as field width, padding, and left or
			right justification. The following is a simple example.
		</p>
<em>Example 5.1: Sample usage of a PatternLayout (examples/chapter5/PatternSample.java)</em>
<div class="source">public class PatternSample {

  static public void main(String[] args) throws Exception {
    Logger rootLogger = (Logger) LoggerFactory.getLogger("root");
    
    <b>PatternLayout layout = new PatternLayout();
    layout.setPattern("%-5level [%thread]: %message%n");
    layout.start();</b>
    
    ConsoleAppender appender = new ConsoleAppender();
    appender.setContext(rootLogger.getLoggerContext());
    appender.setLayout(layout);
    appender.start();
    
    rootLogger.addAppender(appender);

    rootLogger.debug("Message 1");
    rootLogger.warn("Message 2");
  }
}</div>

		<p>
			The conversion pattern is set to be "%-5level [%thread]: %message%n". 
			Running PatternSample will yield the following output on the console. 
		</p>
<div class="source">DEBUG [main]: Message 1
WARN  [main]: Message 2</div>
		<p>
				Note that in the conversion pattern "%-5level [%thread]: %message%n" 
				there is no explicit separator between literal text and conversion 
				specifiers. When parsing a conversion pattern, <code>PatternLayout</code> 
				is capable of differentiating between literal text (space characters, the brackets, 
				colon character) and conversion specifiers. In the example above, 
				the conversion specifier %-5level means the level of the logging event 
				should be left justified to a width of five characters. 
				Format specifiers will be explained in a short moment.
		</p>
		<p>
				The recognized conversion characters and words are
		</p>
		<table border="1" CELLPADDING="8">
			<th>Conversion Character or Word</th>
			<th>Effect</th>

			<tr>
				<td align="center">
					<b>c / l / lo / logger</b>
				</td>

				<td>
					<p>
						Used to output the logger of the logging event.
						The logger conversion specifier can be
						optionally followed by
						<em>precision specifier</em>
						, that is a decimal constant in brackets.
					</p>
					<p>
						If a precision specifier is given, then only the
						corresponding number of right most components of
						the logger name will be printed. By default the
						logger name is printed in full.
					</p>
					<p>
						For example, for the category name "a.b.c" the
						pattern
						<b>%logger{2}</b>
						will output "b.c". See more examples of name
						abbreviations further down this document.
					</p>
				</td>
			</tr>

			<tr>
				<td align="center">
					<b>C / class</b>
				</td>

				<td>
					<p>
						Used to output the fully qualified class name of
						the caller issuing the logging request. This
						conversion specifier can be optionally followed
						by
						<em>precision specifier</em>
						, that is a decimal constant in brackets.
					</p>
					<p>
						If a precision specifier is given, then only the
						corresponding number of right most components of
						the class name will be printed. By default the
						class name is output in fully qualified form.
					</p>
					<p>
						For example, for the class name
						"ch.logback.xyz.SomeClass", the pattern
						<b>%class{1}</b>
						will output "SomeClass". See more examples of
						name abbreviations further down this document.
					</p>
					<p>
						<b>WARNING</b>
						Generating the caller class information is slow.
						Thus, it's use should be avoided unless
						execution speed is not an issue.
					</p>
				</td>
			</tr>

			<tr>
				<td align="center">
					<b>d / date</b>
				</td>
				<td>
					<p>Used to output the date of the logging event. The
					date conversion specifier may be followed by a set
					of braces containing a date and time pattern strings
					{@link java.text.SimpleDateFormat},
					<em>ABSOLUTE</em>
					,
					<em>DATE</em>
					or
					<em>ISO8601</em>
					. 
					</p>
					<p>For example,
					<b>%d{HH:mm:ss,SSS}</b>
					,
					<b>%d{dd&#160;MMM&#160;yyyy&#160;;HH:mm:ss,SSS}</b>
					or
					<b>%d{DATE}</b>
					. If no date format specifier is given then ISO8601
					format is assumed.
					</p>
				</td>
			</tr>

			<tr>
				<td align="center">
					<b>F / file</b>
				</td>

				<td>
					<p>
						Used to output the file name where the logging
						request was issued.
					</p>
					<p>
						<b>WARNING</b>
						Generating caller file information is extremely
						slow. Its use should be avoided unless execution
						speed is not an issue.
					</p>
				</td>
			</tr>

			<tr>
				<td align="center">
					<b>caller</b>
				</td>

				<td>
					<p>
						Used to output location information of the
						caller which generated the logging event.
					</p>
					<p>
						The location information depends on the JVM
						implementation but usually consists of the fully
						qualified name of the calling method followed by
						the caller's source the file name and line
						number between parentheses.
					</p>
					<p>
						The location information can be very useful.
						However, it's generation is
						<em>extremely</em>
						slow. It's use should be avoided unless
						execution speed is not an issue.
					</p>
					<p>
						A precision specifier can be appended to the <em>caller</em> conversion
						specifier to configure the depth of the information to be displayed.
					</p>
				</td>
			</tr>

			<tr>
				<td align="center">
					<b>L / line</b>
				</td>

				<td>
					<p>
						Used to output the line number from where the
						logging request was issued.
					</p>
					<p>
						<b>WARNING</b>
						Generating caller location information is
						extremely slow. It's use should be avoided
						unless execution speed is not an issue.
					</p>
				</td>
			</tr>


			<tr>
				<td align="center">
					<b>m / msg / message</b>
				</td>
				<td>
					Used to output the application supplied message
					associated with the logging event.
				</td>
			</tr>

			<tr>
				<td align="center">
					<b>M / method</b>
				</td>

				<td>
					<p>
						Used to output the method name where the logging
						request was issued.
					</p>
					<p>
						<b>WARNING</b>
						Generating caller location information is
						extremely slow. It's use should be avoided
						unless execution speed is not an issue.
					</p>
				</td>
			</tr>

			<tr>
				<td align="center">
					<b>n</b>
				</td>

				<td>
					<p>
						Outputs the platform dependent line separator
						character or characters.
					</p>
					<p>
						This conversion character offers practically the
						same performance as using non-portable line
						separator strings such as "\n", or "\r\n". Thus,
						it is the preferred way of specifying a line
						separator.
					</p>
				</td>

			</tr>

			<tr>
				<td align="center">
					<b>p / le / level</b>
				</td>
				<td>Used to output the level of the logging event.</td>
			</tr>

			<tr>

				<td align="center">
					<b>r / relative</b>
				</td>

				<td>
					Used to output the number of milliseconds elapsed
					since the start of the application until the
					creation of the logging event.
				</td>
			</tr>


			<tr>
				<td align="center">
					<b>t / thread</b>
				</td>

				<td>
					Used to output the name of the thread that generated
					the logging event.
				</td>

			</tr>

			<tr>
				<td align="center">
					<b>X / mdc</b>
				</td>

				<td>

					<p>
						Used to output the MDC (mapped diagnostic
						context) associated with the thread that
						generated the logging event. 
					</p>
					<p>
						The
						<b>X</b>
						conversion character can be followed by the key
						for the map placed between braces, as in
						<b>%X{clientNumber}</b>
						where
						<code>clientNumber</code>
						is the key. The value in the MDC corresponding
						to the key will be output. 
					</p>
					<p>
						If no additional
						sub-option is specified, then the entire
						contents of the MDC key value pair set is output
						using a format key1=val1, key2=val2
					</p>

					<p>
						See
						<a
							href="http://logback.qos.ch/apidocs/ch/qos/logback/classic/MDC.html">
							MDC
						</a>
						class for more details.
					</p>

				</td>
			</tr>
			<tr>
				<td align="center">
					<b>throwable</b>
				</td>

				<td>
					<p>
						Used to output the Throwable trace that has been
						bound to the LoggingEvent, by default this will
						output the full trace as one would normally find
						by a call to Throwable.printStackTrace(). The
						throwable conversion word can be followed by an
						option in the form
						<b>%throwable{short}</b>
						which will only output the first line of the
						ThrowableInformation.
					</p>
				</td>
			</tr>

			<tr>

				<td align="center">
					<b>%</b>
				</td>

				<td>The sequence %% outputs a single percent sign.</td>
			</tr>

		</table>
		<p>
			By default the relevant information is output as is.
			However, with the aid of format modifiers it is possible to
			change the minimum field width, the maximum field width and
			justification.
		</p>
		<p>
			The optional format modifier is placed between the percent
			sign and the conversion character or word.
		</p>
		<p>
			The first optional format modifier is the
			<em>left justification flag</em>
			which is just the minus (-) character. Then comes the
			optional
			<em>minimum field width</em>
			modifier. This is a decimal constant that represents the
			minimum number of characters to output. If the data item
			requires fewer characters, it is padded on either the left
			or the right until the minimum width is reached. The default
			is to pad on the left (right justify) but you can specify
			right padding with the left justification flag. The padding
			character is space. If the data item is larger than the
			minimum field width, the field is expanded to accommodate
			the data. The value is never truncated.
		</p>
		<p>
			This behavior can be changed using the
			<em>maximum field width</em>
			modifier which is designated by a period followed by a
			decimal constant. If the data item is longer than the
			maximum field, then the extra characters are removed from
			the
			<em>beginning</em>
			of the data item and not from the end. For example, it the
			maximum field width is eight and the data item is ten
			characters long, then the first two characters of the data
			item are dropped. This behavior deviates from the printf
			function in C where truncation is done from the end.
		</p>
		<p>
			Below are various format modifier examples for the logger
			conversion specifier.
		</p>

		<table BORDER="1" CELLPADDING="8">
			<th>Format modifier</th>
			<th>Left justify</th>
			<th>Minimum width</th>
			<th>Maximum width</th>
			<th>Comment</th>

			<tr>
				<td align="center">%20c</td>
				<td align="center">false</td>
				<td align="center">20</td>
				<td align="center">none</td>
				<td>
					Left pad with spaces if the category name is less
					than 20 characters long.
				</td>
			</tr>
			<tr>
				<td align="center">%-20c</td>
				<td align="center">true</td>
				<td align="center">20</td>
				<td align="center">none</td>
				<td>
					Right pad with spaces if the logger name is less
					than 20 characters long.
				</td>
			</tr>
			<tr>
				<td align="center">%.30c</td>
				<td align="center">NA</td>
				<td align="center">none</td>
				<td align="center">30</td>
				<td>
					Truncate from the beginning if the logger name is
					longer than 30 characters.
				</td>
			</tr>
			<tr>
				<td align="center">%20.30c</td>
				<td align="center">false</td>
				<td align="center">20</td>
				<td align="center">30</td>
				<td>
					Left pad with spaces if the logger name is shorter
					than 20 characters. However, if logger name is
					longer than 30 characters, then truncate from the
					beginning.
				</td>
			</tr>
			<tr>
				<td align="center">%-20.30c</td>
				<td align="center">true</td>
				<td align="center">20</td>
				<td align="center">30</td>
				<td>
					Right pad with spaces if the logger name is shorter
					than 20 characters. However, if logger name is
					longer than 30 characters, then truncate from the
					beginning.
				</td>
			</tr>
		</table>
		
		
		<h3>Option handling</h3>
		
		<p>A conversion specifier can be followed by options between curled brackets.
			 We have already seen some of the possibilities offered by logback's option handling
			 with, for example, the MDC conversion specifier: <em>%mdc{someKey}</em>.
		</p>
		<p>
			However, there is much more to it than that.
		</p>
		<p>
			The logger name conversion specifier can take an integer as a first option.
			This will use logback's abbreviation mechanism to display a shorter logger name, 
			without loosing it's meaning.
		</p>
		
		<p>
			The next table should clear things up.
		</p>

		<table BORDER="1" CELLPADDING="8">

			<tr>
				<th>Conversion Pattern</th>
				<th>Logger name</th>
				<th>Result</th>
			</tr>

			<tr>
				<td>%logger{10}</td>
				<td>mainPackage.sub.sample.Bar</td>
				<td>m.s.s.Bar</td>
			</tr>

			<tr>
				<td>%logger{15}</td>
				<td>mainPackage.sub.sample.Bar</td>
				<td>m.s.sample.Bar</td>
			</tr>

			<tr>
				<td>%logger{16}</td>
				<td>mainPackage.sub.sample.Bar</td>
				<td>m.sub.sample.Bar</td>
			</tr>

			<tr>
				<td>%logger{26}</td>
				<td>mainPackage.sub.sample.Bar</td>
				<td>mainPackage.sub.sample.Bar</td>
			</tr>
		</table>
		
		<p>
			Another very useful way of adding options to a conversion specifier is
			when <code>PatternLayout</code> is used with <code>EventEvaluators</code>.
		</p>
		<p>
			<code>EventEvaluators</code> have the responsability to check wether a give event
			matches a give criteria. 
		</p>
		<p>
			Let's look at an example using <code>EventEvaluators</code>. The following
			configuration file outputs the logging events to the console, displaying 
			date, thread, level, message and caller data. 
		</p>
		<p>
			Since displaying the caller data of a logging event is very expensive, this
			information will be displayed only when the logging request is combined with
			a specific marker. By doing that, we make sure that only the most important
			logging requests will have their caller information generated and displayed,
			without penalizing application performance.
		</p>

		<p>
			Here is how to configure logback to behave like we described:
		</p>
<em>Example 5.2: Sample usage of EventEvaluators (examples/chapter5/eventEvaluatorConfig.xml)</em>
<div class="source">
&lt;configuration>

	<b>&lt;evaluator name="DISPLAY_EVAL">
		&lt;Expression>(marker.contains("DISPLAY"))&lt;/Expression>
	&lt;/evaluator></b>
	
  &lt;appender name="STDOUT"
    class="ch.qos.logback.core.ConsoleAppender">
    &lt;layout class="ch.qos.logback.classic.PatternLayout">
      &lt;param name="Pattern"
        value="%-4relative [%thread] %-5level - %msg <b>%caller{2, DISPLAY_EVAL}</b>%n" />
    &lt;/layout>
  &lt;/appender>

  &lt;root>
    &lt;level value="debug" />
    &lt;appender-ref ref="STDOUT" />
  &lt;/root>
&lt;/configuration>
</div>
		<p>
			Let's test this configuration with the following code:
		</p>
<em>Example 5.2: Sample usage of EventEvaluators (examples/chapter5/EventEvaluatorExample.java)</em>
<div class="source">public class EventEvaluatorExample {

  public static void main(String[] args) throws InterruptedException {
    Logger logger = (Logger) LoggerFactory.getLogger(EventEvaluatorExample.class);
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(lc);
    configurator.doConfigure(args[0]);

    for (int i = 0; i &lt; 5; i++) {
      if (i == 3) {
        Marker displayMarker = MarkerFactory.getMarker("DISPLAY");
        logger.debug(displayMarker, "logging statement" + i);
      } else {
        logger.debug("logging statement" + i);
      }
    }
  }
}</div>
		<p>
			This class configures logback with the file given as an argument of
			<code>main()</code> and sends 5 logging requests. The third one
			is associated with a marker named <em>DISPLAY</em>.
		</p>
		<p>
			When a logging request is sent, the corresponding logging event 
			will pass through the evaluation process. Here, obviously, the
			third request will match the evaluation, causing its caller data
			to be displayed.
		</p>
		<p>
			Here is the output of the <code>EventEvaluatorExample</code> class.
		</p>
<div class="source">0    [main] DEBUG - logging statement0 
0    [main] DEBUG - logging statement1 
0    [main] DEBUG - logging statement2 
0    [main] DEBUG - logging statement3 Caller+0	 at chapter5.EventEvaluatorExample.main(EventEvaluatorExample.java:25)

16   [main] DEBUG - logging statement4 </div>




		<h3>HTMLLayout</h3>

			<em>
				Example 1.1: Basic template for logging
				(examples/chapter1/HelloWorld1.java)
			</em>





			<h2>Logback access</h2>
			<h3>PatternLayout</h3>
			<h3>HTMLLayout</h3>

</body>
</document>
