This file is indexed.

/usr/share/doc/liblogback-java/manual/mdc.html is in liblogback-java-doc 1:1.1.3-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
<!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 8: Mapped Diagnostic Context</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/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 8: Mapped Diagnostic Context</h1>

    <div class="quote">     
      <p><em>Lock the doors.</em></p>
      <p>&mdash;LEROY CAIN, Flight Director, Columbia Mission Control</p>
    </div>
    
    <script src="../templates/creative.js" type="text/javascript"></script>
    
		<p>One of the design goals of logback is to audit and debug
		complex distributed applications.  Most real-world distributed
		systems need to deal with multiple clients simultaneously.  In a
		typical multithreaded implementation of such a system, different
		threads will handle different clients. A possible but slightly
		discouraged approach to differentiate the logging output of one
		client from another consists of instantiating a new and separate
		logger for each client.  This technique promotes the proliferation
		of loggers and may increase their management overhead.
		</p>
		
    <script src="../templates/setup.js" type="text/javascript"></script>

    
    <p>A lighter technique consists of uniquely stamping each log
   	request servicing a given client. Neil Harrison described this
   	method in the book <em>Patterns for Logging Diagnostic
   	Messages</em> in Pattern Languages of Program Design 3, edited by
   	R. Martin, D. Riehle, and F. Buschmann (Addison-Wesley,
   	1997). Logback leverages a variant of this technique included in
   	the SLF4J API: Mapped Diagnostic Contexts (MDC).
		</p>
		
		<p>To uniquely stamp each request, the user puts contextual
		information into the <code>MDC</code>, the abbreviation of Mapped
		Diagnostic Context.  The salient parts of the MDC class are shown
		below. Please refer to the <a
		href="http://www.slf4j.org/api/org/slf4j/MDC.html">MDC
		javadocs</a> for a complete list of methods.
		</p>

<pre class="prettyprint source">package org.slf4j;

public class MDC {
  //Put a context value as identified by <em>key</em>
  //into the current thread's context map.
  <b>public static void put(String key, String val);</b>

  //Get the context identified by the <code>key</code> parameter.
  <b>public static String get(String key);</b>

  //Remove the context identified by the <code>key</code> parameter.
  <b>public static void remove(String key);</b>

  //Clear all entries in the MDC.
  <b>public static void clear();</b>
}</pre>

		<p>The <code>MDC</code> class contains only static methods.  It
		lets the developer place information in a <em>diagnostic
		context</em> that can be subsequently retrieved by certain logback
		components. The <code>MDC</code> manages contextual information on
		a <em>per thread basis</em>.  A child thread automatically
		inherits a <em>copy</em> of the mapped diagnostic context of its
		parent. Typically, while starting to service a new client request,
		the developer will insert pertinent contextual information, such
		as the client id, client's IP address, request parameters
		etc. into the <code>MDC</code>. Logback components, if
		appropriately configured, will automatically include this
		information in each log entry.
		</p>

    <p>Please note that MDC as implemented by logback-classic assumes
    that values are placed into the MDC with moderate frequency. </p>

		<p>
			The next application named 
			<code><a href="../xref/chapters/mdc/SimpleMDC.html">SimpleMDC</a></code> 
			demonstrates this basic principle.
		</p>
<em>Example 7.1: Basic MDC usage (<a href="../xref/chapters/mdc/SimpleMDC.html">
logback-examples/src/main/java/chapters/mdc/SimpleMDC.java)</a></em>
<pre class="prettyprint source">package chapters.mdc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.core.ConsoleAppender;

public class SimpleMDC {
  static public void main(String[] args) throws Exception {

    // You can put values in the MDC at any time. Before anything else
    // we put the first name
    MDC.put("first", "Dorothy");

    [ SNIP ]
    
    Logger logger = LoggerFactory.getLogger(SimpleMDC.class);
    // We now put the last name
    MDC.put("last", "Parker");

    // The most beautiful two words in the English language according
    // to Dorothy Parker:
    logger.info("Check enclosed.");
    logger.debug("The most beautiful two words in English.");

    MDC.put("first", "Richard");
    MDC.put("last", "Nixon");
    logger.info("I am not a crook.");
    logger.info("Attributed to the former US president. 17 Nov 1973.");
  }

  [ SNIP ]

}</pre>

		<p>The main method starts by associating the value
		<em>Dorothy</em> with the key <em>first</em> in the
		<code>MDC</code>. You can place as many value/key associations in
		the <code>MDC</code> as you wish.  Multiple insertions with the
		same key will overwrite older values.  The code then proceeds to
		configure logback.</p>

    <p>For the sake of conciseness, we have the omitted the code that
    configures logback with the configuration file <a
    href="http://github.com/qos-ch/logback/blob/master/logback-examples/src/main/java/chapters/mdc/simpleMDC.xml">simpleMDC.xml</a>. Here
    is the relevant section from that file.
    </p>

 <pre class="prettyprint source">&lt;appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> 
  &lt;layout>
    &lt;Pattern><b>%X{first} %X{last}</b> - %m%n&lt;/Pattern>
  &lt;/layout> 
&lt;/appender></pre>
    


    <p>Note the usage of the <em>%X</em> specifier within the
    <code>PatternLayout</code> conversion pattern. The <em>%X</em>
    conversion specifier is employed twice, once for the key named
    <em>first</em> and once for the key named <em>last</em>. After
    obtaining a logger corresponding to <code>SimpleMDC.class</code>,
    the code associates the value <em>Parker</em> with the key named
    <em>last</em>.  It then invokes the logger twice with different
    messages.  The code finishes by setting the <code>MDC</code> to
    different values and issuing several logging requests. Running
    SimpleMDC yields:
		</p>

<div class="source"><pre>Dorothy Parker - Check enclosed.
Dorothy Parker - The most beautiful two words in English.
Richard Nixon - I am not a crook.
Richard Nixon - Attributed to the former US president. 17 Nov 1973.</pre></div>


		<p>The <code>SimpleMDC</code> application illustrates how logback
		layouts, if configured appropriately, can automatically output
		<code>MDC</code> information.  Moreover, the information placed
		into the <code>MDC</code> can be used by multiple logger
		invocations.
		</p>
		
		<h3 class="doAnchor">Advanced Use</h3>
		
		<p>Mapped Diagnostic Contexts shine brightest within client server
		architectures.  Typically, multiple clients will be served by
		multiple threads on the server.  Although the methods in the
		<code>MDC</code> class are static, the diagnostic context is
		managed on a per thread basis, allowing each server thread to bear
		a distinct <code>MDC</code> stamp. <code>MDC</code> operations
		such as <code>put()</code> and <code>get()</code> affect only the
		<code>MDC</code> of the <em>current</em> thread, and the children
		of the current thread. The <code>MDC</code> in other threads
		remain unaffected. Given that <code>MDC</code> information is
		managed on a per thread basis, each thread will have its own copy
		of the <code>MDC</code>.  Thus, there is no need for the developer
		to worry about thread-safety or synchronization when programming
		with the <code>MDC</code> because it handles these issues safely
		and transparently.
		</p>

		<p>The next example is somewhat more advanced.  It shows how the
		<code>MDC</code> can be used in a client-server setting.  The
		server-side implements the <code>NumberCruncher</code> interface
		shown in Example 7.2 below. <code>The NumberCruncher</code>
		interface contains a single method named
		<code>factor()</code>. Using RMI technology, the client invokes
		the <code>factor()</code> method of the server application to
		retrieve the distinct factors of an integer.
		</p>

<em>Example 7.2: The service interface (<a href="../xref/chapters/mdc/NumberCruncher.html">
logback-examples/src/main/java/chapters/mdc/NumberCruncher.java)</a></em>
<pre class="prettyprint source">package chapters.mdc;

import java.rmi.Remote;
import java.rmi.RemoteException;

/**
 * NumberCruncher factors positive integers.
 */
public interface NumberCruncher extends Remote {
  /**
   * Factor a positive integer <code>number</code> and return its
   * <em>distinct</em> factor's as an integer array.
   * */
  int[] factor(int number) throws RemoteException;
}</pre>

		<p>
			The <code>NumberCruncherServer</code> application, listed in Example 7.3 below, 
			implements the <code>NumberCruncher</code> interface. Its main method exports 
			an RMI Registry on the local host that accepts requests on a well-known port.  
		</p>

<em>Example 7.3: The server side (<a href="../xref/chapters/mdc/NumberCruncherServer.html">
logback-examples/src/main/java/chapters/mdc/NumberCruncherServer.java)</a></em>
<pre class="prettyprint source">package chapters.mdc;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Vector;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;


/**
 * A simple NumberCruncher implementation that logs its progress when
 * factoring numbers. The purpose of the whole exercise is to show the
 * use of mapped diagnostic contexts in order to distinguish the log
 * output from different client requests.
 * */
public class NumberCruncherServer extends UnicastRemoteObject
  implements NumberCruncher {

  private static final long serialVersionUID = 1L;

  static Logger logger = LoggerFactory.getLogger(NumberCruncherServer.class);

  public NumberCruncherServer() throws RemoteException {
  }

  public int[] factor(int number) throws RemoteException {
    // The client's host is an important source of information.
    try {
      <b>MDC.put("client", NumberCruncherServer.getClientHost());</b>
    } catch (java.rmi.server.ServerNotActiveException e) {
      logger.warn("Caught unexpected ServerNotActiveException.", e);
    }

    // The information contained within the request is another source
    // of distinctive information. It might reveal the users name,
    // date of request, request ID etc. In servlet type environments,
    // useful information is contained in the HttpRequest or in the  
    // HttpSession.
    <b>MDC.put("number", String.valueOf(number));</b>

    logger.info("Beginning to factor.");

    if (number &lt;= 0) {
      throw new IllegalArgumentException(number +
        " is not a positive integer.");
    } else if (number == 1) {
      return new int[] { 1 };
    }

    Vector&lt;Integer> factors = new Vector&lt;Integer>();
    int n = number;

    for (int i = 2; (i &lt;= n) &amp;&amp; ((i * i) &lt;= number); i++) {
      // It is bad practice to place log requests within tight loops.
      // It is done here to show interleaved log output from
      // different requests. 
      logger.debug("Trying " + i + " as a factor.");

      if ((n % i) == 0) {
        logger.info("Found factor " + i);
        factors.addElement(new Integer(i));

        do {
          n /= i;
        } while ((n % i) == 0);
      }

      // Placing artificial delays in tight loops will also lead to
      // sub-optimal results. :-)
      delay(100);
    }

    if (n != 1) {
      logger.info("Found factor " + n);
      factors.addElement(new Integer(n));
    }

    int len = factors.size();

    int[] result = new int[len];

    for (int i = 0; i &lt; len; i++) {
      result[i] = ((Integer) factors.elementAt(i)).intValue();
    }

    <b>// clean up
    MDC.remove("client");
    MDC.remove("number");</b>

    return result;
  }

  static void usage(String msg) {
    System.err.println(msg);
    System.err.println("Usage: java chapters.mdc.NumberCruncherServer configFile\n" +
      "   where configFile is a logback configuration file.");
    System.exit(1);
  }

  public static void delay(int millis) {
    try {
      Thread.sleep(millis);
    } catch (InterruptedException e) {
    }
  }

  public static void main(String[] args) {
    if (args.length != 1) {
      usage("Wrong number of arguments.");
    }

    String configFile = args[0];

    if (configFile.endsWith(".xml")) {
      try {
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(lc);
        lc.reset();
        configurator.doConfigure(args[0]);
      } catch (JoranException je) {
        je.printStackTrace();
      }
    }

    NumberCruncherServer ncs;

    try {
      ncs = new NumberCruncherServer();
      logger.info("Creating registry.");

      Registry registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
      registry.rebind("Factor", ncs);
      logger.info("NumberCruncherServer bound and ready.");
    } catch (Exception e) {
      logger.error("Could not bind NumberCruncherServer.", e);

      return;
    }
  }
}</pre>

		<p>The implementation of the <code>factor(int number)</code>
		method is of particular relevance. It starts by putting the
		client's hostname into the <code>MDC</code> under the key
		<em>client</em>. The number to factor, as requested by the client,
		is put into the <code>MDC</code> under the key
		<em>number</em>. After computing the distinct factors of the
		integer parameter, the result is returned to the client. Before
		returning the result however, the values for the <em>client</em>
		and <em>number</em> are cleared by calling the
		<code>MDC.remove()</code> method. Normally, a <code>put()</code>
		operation should be balanced by the corresponding
		<code>remove()</code> operation. Otherwise, the <code>MDC</code>
		will contain stale values for certain keys. We would recommend
		that whenever possible, <code>remove()</code> operations be
		performed within finally blocks, ensuring their invocation
		regardless of the execution path of the code.
		</p>	
		
		<p>
			After these theoretical explanations, we are ready to run the number 
			cruncher example. Start the server with the following command:
		</p>
		
<div class="source"><pre>java chapters.mdc.NumberCruncherServer src/main/java/chapters/mdc/mdc1.xml</pre></div>
		
		<p>
			The <em>mdc1.xml</em> configuration file is listed below:
		</p>
<em>Example 7.4: Configuration file (logback-examples/src/main/java/chapters/mdc/mdc1.xml)</em>
<pre class="prettyprint source">&lt;configuration>
  &lt;appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    &lt;layout>
      &lt;Pattern>%-4r [%thread] %-5level <b>C:%X{client} N:%X{number}</b> - %msg%n&lt;/Pattern>
    &lt;/layout>	    
  &lt;/appender>
  
  &lt;root level="debug">
    &lt;appender-ref ref="CONSOLE"/>
  &lt;/root>  
&lt;/configuration></pre>

		<p>
			Note the use of the <em>%X</em> conversion specifier within the 
			<span class="option">Pattern</span> option.
		</p>
	
		<p>
			The following command starts an instance of <code>NumberCruncherClient</code> 
			application:  	
		</p>
		
<div class="source"><pre>java chapters.mdc.NumberCruncherClient <em>hostname</em></pre></div>

		<p>
			where <em>hostname</em> is the host where the 
			<code>NumberCruncherServer</code> is running
		</p>
		
		<p>
			Executing multiple instances of the client and requesting the server to factor 
			the numbers 129 from the first client and shortly thereafter 
			the number 71 from the second client, the server outputs the following:
		</p>
		
<div class="source"><pre>
<b>70984 [RMI TCP Connection(4)-192.168.1.6] INFO  C:orion N:129 - Beginning to factor.</b>
70984 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 2 as a factor.
71093 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 3 as a factor.
71093 [RMI TCP Connection(4)-192.168.1.6] INFO  C:orion N:129 - Found factor 3
71187 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 4 as a factor.
71297 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 5 as a factor.
71390 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 6 as a factor.
<b>71453 [RMI TCP Connection(5)-192.168.1.6] INFO  C:orion N:71 - Beginning to factor.</b>
71453 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 2 as a factor.
71484 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 7 as a factor.
71547 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 3 as a factor.
71593 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 8 as a factor.
71656 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 4 as a factor.
71687 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 9 as a factor.
71750 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 5 as a factor.
71797 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 10 as a factor.
71859 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 6 as a factor.
71890 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 11 as a factor.
71953 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 7 as a factor.
72000 [RMI TCP Connection(4)-192.168.1.6] INFO  C:orion N:129 - Found factor 43
72062 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 8 as a factor.
72156 [RMI TCP Connection(5)-192.168.1.6] INFO  C:orion N:71 - Found factor 71</pre></div>

		<p>
			The clients were run from a machine called <em>orion</em> as can be seen in 
			the above output. Even if the server processes the requests of clients 
			near-simultaneously in separate threads, the logging output pertaining 
			to each client request can be distinguished by studying the output of the 
			<code>MDC</code>. Note for example the stamp associated with <em>number</em>, 
			i.e. the number to factor. 
		</p>
		
		<p>
			The attentive reader might have observed that the thread name could 
			also have been used to distinguish each request. The thread name can cause 
			confusion if the server side technology recycles threads. In that case, 
			it may be hard to determine the boundaries of each request, that is, 
			when a given thread finishes servicing a request and when it begins servicing the next.
			Because the <code>MDC</code> is under the control of the application developer, 
			<code>MDC</code> stamps do not suffer from this problem. 
		</p>
		
		
		
		<h3 class="doAnchor" name="autoMDC">Automating access to the <code>MDC</code></h3>
		
		<p>As we've seen, the <code>MDC</code> is very useful when dealing
			with multiple clients. In the case of a web application that
			manages user authentication, one simple solution could be to set
			the user's name in the <code>MDC</code> and remove it once the
			user logs out. Unfortunately, it is not always possible to
			achieve reliable results using this technique. Since
			<code>MDC</code> manages data on a <em>per thread</em> basis, a
			server that recycles threads might lead to false information
			contained in the <code>MDC</code>.
		</p>
		
		<p>To allow the information contained in the <code>MDC</code> to
			be correct at all times when a request is processed, a possible
			approach would be to store the username at the beginning of the
			process, and remove it at the end of said process. A servlet <a
			href="http://java.sun.com/javaee/5/docs/api/javax/servlet/Filter.html">
			<code>Filter</code></a> comes in handy in this case.
		</p>
		
		<p>Within the servlet filter's <code>doFilter</code> method, we
		can retrieve the relevant user data through the request (or a
		cookie therein), store it the <code>MDC</code>.  Subsequent
		processing by other filters and servlets will automatically
		benefit from the MDC data that was stored previously. Finally,
		when our servlet filter regains control, we have an opportunity to
		clean MDC data.
		</p>
		
		<p>Here is an implementation of such a filter:</p>

<em>Example 7.5: User servlet filter (<a href="../xref/chapters/mdc/UserServletFilter.html">
logback-examples/src/main/java/chapters/mdc/UserServletFilter.java)</a></em>
<pre class="prettyprint source">package chapters.mdc;

import java.io.IOException;
import java.security.Principal;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.MDC;

public class UserServletFilter implements Filter {

  private final String USER_KEY = "username";
  
  public void destroy() {
  }

  public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain) throws IOException, ServletException {

    boolean successfulRegistration = false;

    HttpServletRequest req = (HttpServletRequest) request;    
    Principal principal = req.getUserPrincipal();
    // Please note that we could have also used a cookie to 
    // retrieve the user name

    if (principal != null) {
      String username = principal.getName();
      successfulRegistration = registerUsername(username);
    } 

    try {
      chain.doFilter(request, response);
    } finally {
      if (successfulRegistration) {
        MDC.remove(USER_KEY);
      }
    }
  }

  public void init(FilterConfig arg0) throws ServletException {
  }
  

  /**
   * Register the user in the MDC under USER_KEY.
   * 
   * @param username
   * @return true id the user can be successfully registered
   */
  private boolean registerUsername(String username) {
    if (username != null &amp;&amp; username.trim().length() > 0) {
      MDC.put(USER_KEY, username);
      return true;
    }
    return false;
  }
}</pre>

	<p>When the filter's <code>doFilter()</code> method is called, it
	first looks for a <code>java.security.Principal</code> object in the
	request. This object contains the name of the currently
	authenticated user. If a user information is found, it is registered
	in the <code>MDC</code>.
	</p>
		
	<p>Once the filter chain has completed, the filter removes the user
		information from the <code>MDC</code>.
	</p>

  <p>The approach we just outlined sets MDC data only for the duration
  of the request and only for the thread processing it. Other threads
  are unaffected. Furthermore, any given thread will contain correct
  MDC data at any point in time.</p>
		


  <h3 class="doAnchor" name="managedThreads">MDC And Managed
  Threads</h3>

  <p>A copy of the mapped diagnostic context can not always be
  inherited by worker threads from the initiating thread. This is the
  case when <code>java.util.concurrent.Executors</code> is used for
  thread management. For instance, <code>newCachedThreadPool</code>
  method creates a <code>ThreadPoolExecutor</code> and like other
  thread pooling code, it has intricate thread creation logic.
  </p>

  <p>In such cases, it is recommended that
  <code>MDC.getCopyOfContextMap()</code> is invoked on the original
  (master) thread before submitting a task to the executor.  When the
  task runs, as its first action, it should invoke
  <code>MDC.setContextMapValues()</code> to associate the stored copy
  of the original MDC values with the new <code>Executor</code>
  managed thread.
  </p>

  <h3 class="doAnchor" name="mis">MDCInsertingServletFilter</h3>

  <p>Within web applications, it often proves helpful to know the
  hostname, request uri and user-agent associated with a given HTTP
  request. <a
  href="../xref/ch/qos/logback/classic/helpers/MDCInsertingServletFilter.html"><code>MDCInsertingServletFilter</code></a>
  inserts such data into the MDC under the following keys.
  </p>

  <table class="bodyTable">
    <tr>
      <th>MDC key</th>
      <th>MDC value</th>
    </tr>

    <tr  class="alt">
      <td><code>req.remoteHost</code></td>
      <td>as returned by the <a
      href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletRequest.html#getRemoteHost%28%29">getRemoteHost()</a>
      method
      </td>
    </tr>

    <tr >
      <td><code>req.xForwardedFor</code></td>
      <td>value of the <a
      href="http://en.wikipedia.org/wiki/X-Forwarded-For">"X-Forwarded-For"</a>
      header
      </td>
    </tr>

    <tr class="alt">
      <td><code>req.method</code></td>
      <td>
        as returned by <a
        href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletRequest.html#getMethod%28%29">getMethod()</a>
        method
      </td>
    </tr>

    <tr>
      <td><code>req.requestURI</code></td>
      <td>
        as returned by <a
        href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletRequest.html#getRequestURI%28%29">getRequestURI()</a>
        method
      </td>
    </tr>

    <tr class="alt">
      <td><code>req.requestURL</code></td>
      <td>
        as returned by <a
        href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletRequest.html#getRequestURL%28%29">getRequestURL()</a>
        method
      </td>
    </tr>

    <tr>
      <td><code>req.queryString</code></td>
      <td>
        as returned by <a
        href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletRequest.html#getQueryString%28%29">getQueryString()</a>        method
      </td>
    </tr>

    <tr class="alt">
      <td><code>req.userAgent</code></td>
      <td>value of the "User-Agent" header
      </td>
    </tr>

  </table>

  <p>To install <code>MDCInsertingServletFilter</code> add the
  following lines to your web-application's <em>web.xml</em> file</p>

  <pre class="prettyprint source">&lt;filter>
  &lt;filter-name>MDCInsertingServletFilter&lt;/filter-name>
  &lt;filter-class>
    ch.qos.logback.classic.helpers.MDCInsertingServletFilter
  &lt;/filter-class>
&lt;/filter>
&lt;filter-mapping>
  &lt;filter-name>MDCInsertingServletFilter&lt;/filter-name>
  &lt;url-pattern>/*&lt;/url-pattern>
&lt;/filter-mapping> </pre>

  <p><b>If your web-app has multiple filters, make sure that
  <code>MDCInsertingServletFilter</code> is declared before other
  filters.</b> For example, assuming the main processing in your
  web-app is done in filter 'F', the MDC values set by
  <code>MDCInsertingServletFilter</code> will not be seen by the code
  invoked by 'F' if <code>MDCInsertingServletFilter</code> comes after
  'F'.
  </p>

  <p>Once the filter is installed, values corresponding to each MDC
  key will be output by the %X <a
  href="layouts.html#conversionWord">conversion word</a> according to
  the key passes as first option. For example, to print the remote
  host followed by the request URI on one line, the date followed by
  the message on the next, you would set <code>PatternLayout</code>'s
  pattern to:
  
  </p>

  <p class="source">%X{req.remoteHost} %X{req.requestURI}%n%d - %m%n</p>

  <script src="../templates/footer.js" type="text/javascript"></script>
</div>
</body>
</html>