| 1 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" |
| 2 |
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> |
| 3 |
|
| 4 |
<html xmlns="http://www.w3.org/1999/xhtml"> |
| 5 |
<head> |
| 6 |
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> |
| 7 |
<title>Chapter 8: Mapped Diagnostic Context</title> |
| 8 |
<link rel="stylesheet" type="text/css" href="../css/common.css" /> |
| 9 |
<link rel="stylesheet" type="text/css" href="../css/screen.css" media="screen" /> |
| 10 |
<link rel="stylesheet" type="text/css" href="../css/_print.css" media="print" /> |
| 11 |
<link rel="stylesheet" type="text/css" href="../css/prettify.css" media="screen" /> |
| 12 |
</head> |
| 13 |
<body onload="prettyPrint(); decorate();"> |
| 14 |
<script type="text/javascript">prefix='../';</script> |
| 15 |
<script type="text/javascript" src="../js/prettify.js"></script> |
| 16 |
<script type="text/javascript" src="../templates/header.js"></script> |
| 17 |
<script type="text/javascript" src="../js/jquery-min.js"></script> |
| 18 |
<script type="text/javascript" src="../js/decorator.js"></script> |
| 19 |
|
| 20 |
<div id="left"> |
| 21 |
<noscript>Please turn on Javascript to view this menu</noscript> |
| 22 |
<script src="../templates/left.js" type="text/javascript"></script> |
| 23 |
</div> |
| 24 |
<div id="right"> |
| 25 |
<script src="menu.js" type="text/javascript"></script> |
| 26 |
</div> |
| 27 |
<div id="content"> |
| 28 |
|
| 29 |
<h1>Chapter 8: Mapped Diagnostic Context</h1> |
| 30 |
|
| 31 |
<a href="mdc_ja.html">和訳 (Japanese translation)</a> |
| 32 |
|
| 33 |
<div class="quote"> |
| 34 |
<p><em>Lock the doors.</em></p> |
| 35 |
<p>—LEROY CAIN, Flight Director, Columbia Mission Control</p> |
| 36 |
</div> |
| 37 |
|
| 38 |
<script src="../templates/creative.js" type="text/javascript"></script> |
| 39 |
|
| 40 |
<p>One of the design goals of logback is to audit and debug |
| 41 |
complex distributed applications. Most real-world distributed |
| 42 |
systems need to deal with multiple clients simultaneously. In a |
| 43 |
typical multithreaded implementation of such a system, different |
| 44 |
threads will handle different clients. A possible but slightly |
| 45 |
discouraged approach to differentiate the logging output of one |
| 46 |
client from another consists of instantiating a new and separate |
| 47 |
logger for each client. This technique promotes the proliferation |
| 48 |
of loggers and may increase their management overhead. |
| 49 |
</p> |
| 50 |
|
| 51 |
<script src="../templates/setup.js" type="text/javascript"></script> |
| 52 |
|
| 53 |
|
| 54 |
<p>A lighter technique consists of uniquely stamping each log |
| 55 |
request servicing a given client. Neil Harrison described this |
| 56 |
method in the book <em>Patterns for Logging Diagnostic |
| 57 |
Messages</em> in Pattern Languages of Program Design 3, edited by |
| 58 |
R. Martin, D. Riehle, and F. Buschmann (Addison-Wesley, |
| 59 |
1997). Logback leverages a variant of this technique included in |
| 60 |
the SLF4J API: Mapped Diagnostic Contexts (MDC). |
| 61 |
</p> |
| 62 |
|
| 63 |
<p>To uniquely stamp each request, the user puts contextual |
| 64 |
information into the <code>MDC</code>, the abbreviation of Mapped |
| 65 |
Diagnostic Context. The salient parts of the MDC class are shown |
| 66 |
below. Please refer to the <a |
| 67 |
href="http://www.slf4j.org/api/org/slf4j/MDC.html">MDC |
| 68 |
javadocs</a> for a complete list of methods. |
| 69 |
</p> |
| 70 |
|
| 71 |
<pre class="prettyprint source">package org.slf4j; |
| 72 |
|
| 73 |
public class MDC { |
| 74 |
//Put a context value as identified by <em>key</em> |
| 75 |
//into the current thread's context map. |
| 76 |
<b>public static void put(String key, String val);</b> |
| 77 |
|
| 78 |
//Get the context identified by the <code>key</code> parameter. |
| 79 |
<b>public static String get(String key);</b> |
| 80 |
|
| 81 |
//Remove the context identified by the <code>key</code> parameter. |
| 82 |
<b>public static void remove(String key);</b> |
| 83 |
|
| 84 |
//Clear all entries in the MDC. |
| 85 |
<b>public static void clear();</b> |
| 86 |
}</pre> |
| 87 |
|
| 88 |
<p>The <code>MDC</code> class contains only static methods. It |
| 89 |
lets the developer place information in a <em>diagnostic |
| 90 |
context</em> that can be subsequently retrieved by certain logback |
| 91 |
components. The <code>MDC</code> manages contextual information on |
| 92 |
a <em>per thread basis</em>. Typically, while starting to service |
| 93 |
a new client request, the developer will insert pertinent |
| 94 |
contextual information, such as the client id, client's IP |
| 95 |
address, request parameters etc. into the |
| 96 |
<code>MDC</code>. Logback components, if appropriately configured, |
| 97 |
will automatically include this information in each log entry. |
| 98 |
</p> |
| 99 |
|
| 100 |
<p>Please note that MDC as implemented by logback-classic assumes |
| 101 |
that values are placed into the MDC with moderate frequency. Also |
| 102 |
note that a child thread does not automatically inherit a copy of |
| 103 |
the mapped diagnostic context of its parent.</p> |
| 104 |
|
| 105 |
<p> |
| 106 |
The next application named |
| 107 |
<code><a href="../xref/chapters/mdc/SimpleMDC.html">SimpleMDC</a></code> |
| 108 |
demonstrates this basic principle. |
| 109 |
</p> |
| 110 |
<em>Example 7.1: Basic MDC usage (<a href="../xref/chapters/mdc/SimpleMDC.html"> |
| 111 |
logback-examples/src/main/java/chapters/mdc/SimpleMDC.java)</a></em> |
| 112 |
<pre class="prettyprint source">package chapters.mdc; |
| 113 |
|
| 114 |
import org.slf4j.Logger; |
| 115 |
import org.slf4j.LoggerFactory; |
| 116 |
import org.slf4j.MDC; |
| 117 |
|
| 118 |
import ch.qos.logback.classic.PatternLayout; |
| 119 |
import ch.qos.logback.core.ConsoleAppender; |
| 120 |
|
| 121 |
public class SimpleMDC { |
| 122 |
static public void main(String[] args) throws Exception { |
| 123 |
|
| 124 |
// You can put values in the MDC at any time. Before anything else |
| 125 |
// we put the first name |
| 126 |
MDC.put("first", "Dorothy"); |
| 127 |
|
| 128 |
[ SNIP ] |
| 129 |
|
| 130 |
Logger logger = LoggerFactory.getLogger(SimpleMDC.class); |
| 131 |
// We now put the last name |
| 132 |
MDC.put("last", "Parker"); |
| 133 |
|
| 134 |
// The most beautiful two words in the English language according |
| 135 |
// to Dorothy Parker: |
| 136 |
logger.info("Check enclosed."); |
| 137 |
logger.debug("The most beautiful two words in English."); |
| 138 |
|
| 139 |
MDC.put("first", "Richard"); |
| 140 |
MDC.put("last", "Nixon"); |
| 141 |
logger.info("I am not a crook."); |
| 142 |
logger.info("Attributed to the former US president. 17 Nov 1973."); |
| 143 |
} |
| 144 |
|
| 145 |
[ SNIP ] |
| 146 |
|
| 147 |
}</pre> |
| 148 |
|
| 149 |
<p>The main method starts by associating the value |
| 150 |
<em>Dorothy</em> with the key <em>first</em> in the |
| 151 |
<code>MDC</code>. You can place as many value/key associations in |
| 152 |
the <code>MDC</code> as you wish. Multiple insertions with the |
| 153 |
same key will overwrite older values. The code then proceeds to |
| 154 |
configure logback.</p> |
| 155 |
|
| 156 |
<p>For the sake of conciseness, we have the omitted the code that |
| 157 |
configures logback with the configuration file <a |
| 158 |
href="http://github.com/qos-ch/logback/blob/master/logback-examples/src/main/java/chapters/mdc/simpleMDC.xml">simpleMDC.xml</a>. Here |
| 159 |
is the relevant section from that file. |
| 160 |
</p> |
| 161 |
|
| 162 |
<pre class="prettyprint source"><appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> |
| 163 |
<layout> |
| 164 |
<Pattern><b>%X{first} %X{last}</b> - %m%n</Pattern> |
| 165 |
</layout> |
| 166 |
</appender></pre> |
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
<p>Note the usage of the <em>%X</em> specifier within the |
| 171 |
<code>PatternLayout</code> conversion pattern. The <em>%X</em> |
| 172 |
conversion specifier is employed twice, once for the key named |
| 173 |
<em>first</em> and once for the key named <em>last</em>. After |
| 174 |
obtaining a logger corresponding to <code>SimpleMDC.class</code>, |
| 175 |
the code associates the value <em>Parker</em> with the key named |
| 176 |
<em>last</em>. It then invokes the logger twice with different |
| 177 |
messages. The code finishes by setting the <code>MDC</code> to |
| 178 |
different values and issuing several logging requests. Running |
| 179 |
SimpleMDC yields: |
| 180 |
</p> |
| 181 |
|
| 182 |
<div class="source"><pre>Dorothy Parker - Check enclosed. |
| 183 |
Dorothy Parker - The most beautiful two words in English. |
| 184 |
Richard Nixon - I am not a crook. |
| 185 |
Richard Nixon - Attributed to the former US president. 17 Nov 1973.</pre></div> |
| 186 |
|
| 187 |
|
| 188 |
<p>The <code>SimpleMDC</code> application illustrates how logback |
| 189 |
layouts, if configured appropriately, can automatically output |
| 190 |
<code>MDC</code> information. Moreover, the information placed |
| 191 |
into the <code>MDC</code> can be used by multiple logger |
| 192 |
invocations. |
| 193 |
</p> |
| 194 |
|
| 195 |
<h3 class="doAnchor">Advanced Use</h3> |
| 196 |
|
| 197 |
<p>Mapped Diagnostic Contexts shine brightest within client server |
| 198 |
architectures. Typically, multiple clients will be served by |
| 199 |
multiple threads on the server. Although the methods in the |
| 200 |
<code>MDC</code> class are static, the diagnostic context is |
| 201 |
managed on a per thread basis, allowing each server thread to bear |
| 202 |
a distinct <code>MDC</code> stamp. <code>MDC</code> operations |
| 203 |
such as <code>put()</code> and <code>get()</code> affect only the |
| 204 |
<code>MDC</code> of the <em>current</em> thread, and the children |
| 205 |
of the current thread. The <code>MDC</code> in other threads |
| 206 |
remain unaffected. Given that <code>MDC</code> information is |
| 207 |
managed on a per thread basis, each thread will have its own copy |
| 208 |
of the <code>MDC</code>. Thus, there is no need for the developer |
| 209 |
to worry about thread-safety or synchronization when programming |
| 210 |
with the <code>MDC</code> because it handles these issues safely |
| 211 |
and transparently. |
| 212 |
</p> |
| 213 |
|
| 214 |
<p>The next example is somewhat more advanced. It shows how the |
| 215 |
<code>MDC</code> can be used in a client-server setting. The |
| 216 |
server-side implements the <code>NumberCruncher</code> interface |
| 217 |
shown in Example 7.2 below. <code>The NumberCruncher</code> |
| 218 |
interface contains a single method named |
| 219 |
<code>factor()</code>. Using RMI technology, the client invokes |
| 220 |
the <code>factor()</code> method of the server application to |
| 221 |
retrieve the distinct factors of an integer. |
| 222 |
</p> |
| 223 |
|
| 224 |
<em>Example 7.2: The service interface (<a href="../xref/chapters/mdc/NumberCruncher.html"> |
| 225 |
logback-examples/src/main/java/chapters/mdc/NumberCruncher.java)</a></em> |
| 226 |
<pre class="prettyprint source">package chapters.mdc; |
| 227 |
|
| 228 |
import java.rmi.Remote; |
| 229 |
import java.rmi.RemoteException; |
| 230 |
|
| 231 |
/** |
| 232 |
* NumberCruncher factors positive integers. |
| 233 |
*/ |
| 234 |
public interface NumberCruncher extends Remote { |
| 235 |
/** |
| 236 |
* Factor a positive integer <code>number</code> and return its |
| 237 |
* <em>distinct</em> factor's as an integer array. |
| 238 |
* */ |
| 239 |
int[] factor(int number) throws RemoteException; |
| 240 |
}</pre> |
| 241 |
|
| 242 |
<p> |
| 243 |
The <code>NumberCruncherServer</code> application, listed in Example 7.3 below, |
| 244 |
implements the <code>NumberCruncher</code> interface. Its main method exports |
| 245 |
an RMI Registry on the local host that accepts requests on a well-known port. |
| 246 |
</p> |
| 247 |
|
| 248 |
<em>Example 7.3: The server side (<a href="../xref/chapters/mdc/NumberCruncherServer.html"> |
| 249 |
logback-examples/src/main/java/chapters/mdc/NumberCruncherServer.java)</a></em> |
| 250 |
<pre class="prettyprint source">package chapters.mdc; |
| 251 |
|
| 252 |
import java.rmi.RemoteException; |
| 253 |
import java.rmi.registry.LocateRegistry; |
| 254 |
import java.rmi.registry.Registry; |
| 255 |
import java.rmi.server.UnicastRemoteObject; |
| 256 |
import java.util.Vector; |
| 257 |
|
| 258 |
import org.slf4j.Logger; |
| 259 |
import org.slf4j.LoggerFactory; |
| 260 |
import org.slf4j.MDC; |
| 261 |
|
| 262 |
import ch.qos.logback.classic.LoggerContext; |
| 263 |
import ch.qos.logback.classic.joran.JoranConfigurator; |
| 264 |
import ch.qos.logback.core.joran.spi.JoranException; |
| 265 |
|
| 266 |
|
| 267 |
/** |
| 268 |
* A simple NumberCruncher implementation that logs its progress when |
| 269 |
* factoring numbers. The purpose of the whole exercise is to show the |
| 270 |
* use of mapped diagnostic contexts in order to distinguish the log |
| 271 |
* output from different client requests. |
| 272 |
* */ |
| 273 |
public class NumberCruncherServer extends UnicastRemoteObject |
| 274 |
implements NumberCruncher { |
| 275 |
|
| 276 |
private static final long serialVersionUID = 1L; |
| 277 |
|
| 278 |
static Logger logger = LoggerFactory.getLogger(NumberCruncherServer.class); |
| 279 |
|
| 280 |
public NumberCruncherServer() throws RemoteException { |
| 281 |
} |
| 282 |
|
| 283 |
public int[] factor(int number) throws RemoteException { |
| 284 |
// The client's host is an important source of information. |
| 285 |
try { |
| 286 |
<b>MDC.put("client", NumberCruncherServer.getClientHost());</b> |
| 287 |
} catch (java.rmi.server.ServerNotActiveException e) { |
| 288 |
logger.warn("Caught unexpected ServerNotActiveException.", e); |
| 289 |
} |
| 290 |
|
| 291 |
// The information contained within the request is another source |
| 292 |
// of distinctive information. It might reveal the users name, |
| 293 |
// date of request, request ID etc. In servlet type environments, |
| 294 |
// useful information is contained in the HttpRequest or in the |
| 295 |
// HttpSession. |
| 296 |
<b>MDC.put("number", String.valueOf(number));</b> |
| 297 |
|
| 298 |
logger.info("Beginning to factor."); |
| 299 |
|
| 300 |
if (number <= 0) { |
| 301 |
throw new IllegalArgumentException(number + |
| 302 |
" is not a positive integer."); |
| 303 |
} else if (number == 1) { |
| 304 |
return new int[] { 1 }; |
| 305 |
} |
| 306 |
|
| 307 |
Vector<Integer> factors = new Vector<Integer>(); |
| 308 |
int n = number; |
| 309 |
|
| 310 |
for (int i = 2; (i <= n) && ((i * i) <= number); i++) { |
| 311 |
// It is bad practice to place log requests within tight loops. |
| 312 |
// It is done here to show interleaved log output from |
| 313 |
// different requests. |
| 314 |
logger.debug("Trying " + i + " as a factor."); |
| 315 |
|
| 316 |
if ((n % i) == 0) { |
| 317 |
logger.info("Found factor " + i); |
| 318 |
factors.addElement(new Integer(i)); |
| 319 |
|
| 320 |
do { |
| 321 |
n /= i; |
| 322 |
} while ((n % i) == 0); |
| 323 |
} |
| 324 |
|
| 325 |
// Placing artificial delays in tight loops will also lead to |
| 326 |
// sub-optimal results. :-) |
| 327 |
delay(100); |
| 328 |
} |
| 329 |
|
| 330 |
if (n != 1) { |
| 331 |
logger.info("Found factor " + n); |
| 332 |
factors.addElement(new Integer(n)); |
| 333 |
} |
| 334 |
|
| 335 |
int len = factors.size(); |
| 336 |
|
| 337 |
int[] result = new int[len]; |
| 338 |
|
| 339 |
for (int i = 0; i < len; i++) { |
| 340 |
result[i] = ((Integer) factors.elementAt(i)).intValue(); |
| 341 |
} |
| 342 |
|
| 343 |
<b>// clean up |
| 344 |
MDC.remove("client"); |
| 345 |
MDC.remove("number");</b> |
| 346 |
|
| 347 |
return result; |
| 348 |
} |
| 349 |
|
| 350 |
static void usage(String msg) { |
| 351 |
System.err.println(msg); |
| 352 |
System.err.println("Usage: java chapters.mdc.NumberCruncherServer configFile\n" + |
| 353 |
" where configFile is a logback configuration file."); |
| 354 |
System.exit(1); |
| 355 |
} |
| 356 |
|
| 357 |
public static void delay(int millis) { |
| 358 |
try { |
| 359 |
Thread.sleep(millis); |
| 360 |
} catch (InterruptedException e) { |
| 361 |
} |
| 362 |
} |
| 363 |
|
| 364 |
public static void main(String[] args) { |
| 365 |
if (args.length != 1) { |
| 366 |
usage("Wrong number of arguments."); |
| 367 |
} |
| 368 |
|
| 369 |
String configFile = args[0]; |
| 370 |
|
| 371 |
if (configFile.endsWith(".xml")) { |
| 372 |
try { |
| 373 |
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); |
| 374 |
JoranConfigurator configurator = new JoranConfigurator(); |
| 375 |
configurator.setContext(lc); |
| 376 |
lc.reset(); |
| 377 |
configurator.doConfigure(args[0]); |
| 378 |
} catch (JoranException je) { |
| 379 |
je.printStackTrace(); |
| 380 |
} |
| 381 |
} |
| 382 |
|
| 383 |
NumberCruncherServer ncs; |
| 384 |
|
| 385 |
try { |
| 386 |
ncs = new NumberCruncherServer(); |
| 387 |
logger.info("Creating registry."); |
| 388 |
|
| 389 |
Registry registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT); |
| 390 |
registry.rebind("Factor", ncs); |
| 391 |
logger.info("NumberCruncherServer bound and ready."); |
| 392 |
} catch (Exception e) { |
| 393 |
logger.error("Could not bind NumberCruncherServer.", e); |
| 394 |
|
| 395 |
return; |
| 396 |
} |
| 397 |
} |
| 398 |
}</pre> |
| 399 |
|
| 400 |
<p>The implementation of the <code>factor(int number)</code> |
| 401 |
method is of particular relevance. It starts by putting the |
| 402 |
client's hostname into the <code>MDC</code> under the key |
| 403 |
<em>client</em>. The number to factor, as requested by the client, |
| 404 |
is put into the <code>MDC</code> under the key |
| 405 |
<em>number</em>. After computing the distinct factors of the |
| 406 |
integer parameter, the result is returned to the client. Before |
| 407 |
returning the result however, the values for the <em>client</em> |
| 408 |
and <em>number</em> are cleared by calling the |
| 409 |
<code>MDC.remove()</code> method. Normally, a <code>put()</code> |
| 410 |
operation should be balanced by the corresponding |
| 411 |
<code>remove()</code> operation. Otherwise, the <code>MDC</code> |
| 412 |
will contain stale values for certain keys. We would recommend |
| 413 |
that whenever possible, <code>remove()</code> operations be |
| 414 |
performed within finally blocks, ensuring their invocation |
| 415 |
regardless of the execution path of the code. |
| 416 |
</p> |
| 417 |
|
| 418 |
<p> |
| 419 |
After these theoretical explanations, we are ready to run the number |
| 420 |
cruncher example. Start the server with the following command: |
| 421 |
</p> |
| 422 |
|
| 423 |
<div class="source"><pre>java chapters.mdc.NumberCruncherServer src/main/java/chapters/mdc/mdc1.xml</pre></div> |
| 424 |
|
| 425 |
<p> |
| 426 |
The <em>mdc1.xml</em> configuration file is listed below: |
| 427 |
</p> |
| 428 |
<em>Example 7.4: Configuration file (logback-examples/src/main/java/chapters/mdc/mdc1.xml)</em> |
| 429 |
<pre class="prettyprint source"><configuration> |
| 430 |
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> |
| 431 |
<layout> |
| 432 |
<Pattern>%-4r [%thread] %-5level <b>C:%X{client} N:%X{number}</b> - %msg%n</Pattern> |
| 433 |
</layout> |
| 434 |
</appender> |
| 435 |
|
| 436 |
<root level="debug"> |
| 437 |
<appender-ref ref="CONSOLE"/> |
| 438 |
</root> |
| 439 |
</configuration></pre> |
| 440 |
|
| 441 |
<p> |
| 442 |
Note the use of the <em>%X</em> conversion specifier within the |
| 443 |
<span class="option">Pattern</span> option. |
| 444 |
</p> |
| 445 |
|
| 446 |
<p> |
| 447 |
The following command starts an instance of <code>NumberCruncherClient</code> |
| 448 |
application: |
| 449 |
</p> |
| 450 |
|
| 451 |
<div class="source"><pre>java chapters.mdc.NumberCruncherClient <em>hostname</em></pre></div> |
| 452 |
|
| 453 |
<p> |
| 454 |
where <em>hostname</em> is the host where the |
| 455 |
<code>NumberCruncherServer</code> is running |
| 456 |
</p> |
| 457 |
|
| 458 |
<p> |
| 459 |
Executing multiple instances of the client and requesting the server to factor |
| 460 |
the numbers 129 from the first client and shortly thereafter |
| 461 |
the number 71 from the second client, the server outputs the following: |
| 462 |
</p> |
| 463 |
|
| 464 |
<div class="source"><pre> |
| 465 |
<b>70984 [RMI TCP Connection(4)-192.168.1.6] INFO C:orion N:129 - Beginning to factor.</b> |
| 466 |
70984 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 2 as a factor. |
| 467 |
71093 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 3 as a factor. |
| 468 |
71093 [RMI TCP Connection(4)-192.168.1.6] INFO C:orion N:129 - Found factor 3 |
| 469 |
71187 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 4 as a factor. |
| 470 |
71297 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 5 as a factor. |
| 471 |
71390 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 6 as a factor. |
| 472 |
<b>71453 [RMI TCP Connection(5)-192.168.1.6] INFO C:orion N:71 - Beginning to factor.</b> |
| 473 |
71453 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 2 as a factor. |
| 474 |
71484 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 7 as a factor. |
| 475 |
71547 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 3 as a factor. |
| 476 |
71593 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 8 as a factor. |
| 477 |
71656 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 4 as a factor. |
| 478 |
71687 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 9 as a factor. |
| 479 |
71750 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 5 as a factor. |
| 480 |
71797 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 10 as a factor. |
| 481 |
71859 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 6 as a factor. |
| 482 |
71890 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 11 as a factor. |
| 483 |
71953 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 7 as a factor. |
| 484 |
72000 [RMI TCP Connection(4)-192.168.1.6] INFO C:orion N:129 - Found factor 43 |
| 485 |
72062 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 8 as a factor. |
| 486 |
72156 [RMI TCP Connection(5)-192.168.1.6] INFO C:orion N:71 - Found factor 71</pre></div> |
| 487 |
|
| 488 |
<p> |
| 489 |
The clients were run from a machine called <em>orion</em> as can be seen in |
| 490 |
the above output. Even if the server processes the requests of clients |
| 491 |
near-simultaneously in separate threads, the logging output pertaining |
| 492 |
to each client request can be distinguished by studying the output of the |
| 493 |
<code>MDC</code>. Note for example the stamp associated with <em>number</em>, |
| 494 |
i.e. the number to factor. |
| 495 |
</p> |
| 496 |
|
| 497 |
<p> |
| 498 |
The attentive reader might have observed that the thread name could |
| 499 |
also have been used to distinguish each request. The thread name can cause |
| 500 |
confusion if the server side technology recycles threads. In that case, |
| 501 |
it may be hard to determine the boundaries of each request, that is, |
| 502 |
when a given thread finishes servicing a request and when it begins servicing the next. |
| 503 |
Because the <code>MDC</code> is under the control of the application developer, |
| 504 |
<code>MDC</code> stamps do not suffer from this problem. |
| 505 |
</p> |
| 506 |
|
| 507 |
|
| 508 |
|
| 509 |
<h3 class="doAnchor" name="autoMDC">Automating access to the <code>MDC</code></h3> |
| 510 |
|
| 511 |
<p>As we've seen, the <code>MDC</code> is very useful when dealing |
| 512 |
with multiple clients. In the case of a web application that |
| 513 |
manages user authentication, one simple solution could be to set |
| 514 |
the user's name in the <code>MDC</code> and remove it once the |
| 515 |
user logs out. Unfortunately, it is not always possible to |
| 516 |
achieve reliable results using this technique. Since |
| 517 |
<code>MDC</code> manages data on a <em>per thread</em> basis, a |
| 518 |
server that recycles threads might lead to false information |
| 519 |
contained in the <code>MDC</code>. |
| 520 |
</p> |
| 521 |
|
| 522 |
<p>To allow the information contained in the <code>MDC</code> to |
| 523 |
be correct at all times when a request is processed, a possible |
| 524 |
approach would be to store the username at the beginning of the |
| 525 |
process, and remove it at the end of said process. A servlet <a |
| 526 |
href="http://java.sun.com/javaee/5/docs/api/javax/servlet/Filter.html"> |
| 527 |
<code>Filter</code></a> comes in handy in this case. |
| 528 |
</p> |
| 529 |
|
| 530 |
<p>Within the servlet filter's <code>doFilter</code> method, we |
| 531 |
can retrieve the relevant user data through the request (or a |
| 532 |
cookie therein), store it the <code>MDC</code>. Subsequent |
| 533 |
processing by other filters and servlets will automatically |
| 534 |
benefit from the MDC data that was stored previously. Finally, |
| 535 |
when our servlet filter regains control, we have an opportunity to |
| 536 |
clean MDC data. |
| 537 |
</p> |
| 538 |
|
| 539 |
<p>Here is an implementation of such a filter:</p> |
| 540 |
|
| 541 |
<em>Example 7.5: User servlet filter (<a href="../xref/chapters/mdc/UserServletFilter.html"> |
| 542 |
logback-examples/src/main/java/chapters/mdc/UserServletFilter.java)</a></em> |
| 543 |
<pre class="prettyprint source">package chapters.mdc; |
| 544 |
|
| 545 |
import java.io.IOException; |
| 546 |
import java.security.Principal; |
| 547 |
|
| 548 |
import javax.servlet.Filter; |
| 549 |
import javax.servlet.FilterChain; |
| 550 |
import javax.servlet.FilterConfig; |
| 551 |
import javax.servlet.ServletException; |
| 552 |
import javax.servlet.ServletRequest; |
| 553 |
import javax.servlet.ServletResponse; |
| 554 |
import javax.servlet.http.HttpServletRequest; |
| 555 |
import javax.servlet.http.HttpSession; |
| 556 |
|
| 557 |
import org.slf4j.MDC; |
| 558 |
|
| 559 |
public class UserServletFilter implements Filter { |
| 560 |
|
| 561 |
private final String USER_KEY = "username"; |
| 562 |
|
| 563 |
public void destroy() { |
| 564 |
} |
| 565 |
|
| 566 |
public void doFilter(ServletRequest request, ServletResponse response, |
| 567 |
FilterChain chain) throws IOException, ServletException { |
| 568 |
|
| 569 |
boolean successfulRegistration = false; |
| 570 |
|
| 571 |
HttpServletRequest req = (HttpServletRequest) request; |
| 572 |
Principal principal = req.getUserPrincipal(); |
| 573 |
// Please note that we could have also used a cookie to |
| 574 |
// retrieve the user name |
| 575 |
|
| 576 |
if (principal != null) { |
| 577 |
String username = principal.getName(); |
| 578 |
successfulRegistration = registerUsername(username); |
| 579 |
} |
| 580 |
|
| 581 |
try { |
| 582 |
chain.doFilter(request, response); |
| 583 |
} finally { |
| 584 |
if (successfulRegistration) { |
| 585 |
MDC.remove(USER_KEY); |
| 586 |
} |
| 587 |
} |
| 588 |
} |
| 589 |
|
| 590 |
public void init(FilterConfig arg0) throws ServletException { |
| 591 |
} |
| 592 |
|
| 593 |
|
| 594 |
/** |
| 595 |
* Register the user in the MDC under USER_KEY. |
| 596 |
* |
| 597 |
* @param username |
| 598 |
* @return true id the user can be successfully registered |
| 599 |
*/ |
| 600 |
private boolean registerUsername(String username) { |
| 601 |
if (username != null && username.trim().length() > 0) { |
| 602 |
MDC.put(USER_KEY, username); |
| 603 |
return true; |
| 604 |
} |
| 605 |
return false; |
| 606 |
} |
| 607 |
}</pre> |
| 608 |
|
| 609 |
<p>When the filter's <code>doFilter()</code> method is called, it |
| 610 |
first looks for a <code>java.security.Principal</code> object in the |
| 611 |
request. This object contains the name of the currently |
| 612 |
authenticated user. If a user information is found, it is registered |
| 613 |
in the <code>MDC</code>. |
| 614 |
</p> |
| 615 |
|
| 616 |
<p>Once the filter chain has completed, the filter removes the user |
| 617 |
information from the <code>MDC</code>. |
| 618 |
</p> |
| 619 |
|
| 620 |
<p>The approach we just outlined sets MDC data only for the duration |
| 621 |
of the request and only for the thread processing it. Other threads |
| 622 |
are unaffected. Furthermore, any given thread will contain correct |
| 623 |
MDC data at any point in time.</p> |
| 624 |
|
| 625 |
|
| 626 |
|
| 627 |
<h3 class="doAnchor" name="managedThreads">MDC And Managed |
| 628 |
Threads</h3> |
| 629 |
|
| 630 |
<p>A copy of the mapped diagnostic context can not always be |
| 631 |
inherited by worker threads from the initiating thread. This is the |
| 632 |
case when <code>java.util.concurrent.Executors</code> is used for |
| 633 |
thread management. For instance, <code>newCachedThreadPool</code> |
| 634 |
method creates a <code>ThreadPoolExecutor</code> and like other |
| 635 |
thread pooling code, it has intricate thread creation logic. |
| 636 |
</p> |
| 637 |
|
| 638 |
<p>In such cases, it is recommended that |
| 639 |
<code>MDC.getCopyOfContextMap()</code> is invoked on the original |
| 640 |
(master) thread before submitting a task to the executor. When the |
| 641 |
task runs, as its first action, it should invoke |
| 642 |
<code>MDC.setContextMapValues()</code> to associate the stored copy |
| 643 |
of the original MDC values with the new <code>Executor</code> |
| 644 |
managed thread. |
| 645 |
</p> |
| 646 |
|
| 647 |
<h3 class="doAnchor" name="mis">MDCInsertingServletFilter</h3> |
| 648 |
|
| 649 |
<p>Within web applications, it often proves helpful to know the |
| 650 |
hostname, request uri and user-agent associated with a given HTTP |
| 651 |
request. <a |
| 652 |
href="../xref/ch/qos/logback/classic/helpers/MDCInsertingServletFilter.html"><code>MDCInsertingServletFilter</code></a> |
| 653 |
inserts such data into the MDC under the following keys. |
| 654 |
</p> |
| 655 |
|
| 656 |
<table class="bodyTable"> |
| 657 |
<tr> |
| 658 |
<th>MDC key</th> |
| 659 |
<th>MDC value</th> |
| 660 |
</tr> |
| 661 |
|
| 662 |
<tr class="alt"> |
| 663 |
<td><code>req.remoteHost</code></td> |
| 664 |
<td>as returned by the <a |
| 665 |
href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletRequest.html#getRemoteHost%28%29">getRemoteHost()</a> |
| 666 |
method |
| 667 |
</td> |
| 668 |
</tr> |
| 669 |
|
| 670 |
<tr > |
| 671 |
<td><code>req.xForwardedFor</code></td> |
| 672 |
<td>value of the <a |
| 673 |
href="http://en.wikipedia.org/wiki/X-Forwarded-For">"X-Forwarded-For"</a> |
| 674 |
header |
| 675 |
</td> |
| 676 |
</tr> |
| 677 |
|
| 678 |
<tr class="alt"> |
| 679 |
<td><code>req.method</code></td> |
| 680 |
<td> |
| 681 |
as returned by <a |
| 682 |
href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletRequest.html#getMethod%28%29">getMethod()</a> |
| 683 |
method |
| 684 |
</td> |
| 685 |
</tr> |
| 686 |
|
| 687 |
<tr> |
| 688 |
<td><code>req.requestURI</code></td> |
| 689 |
<td> |
| 690 |
as returned by <a |
| 691 |
href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletRequest.html#getRequestURI%28%29">getRequestURI()</a> |
| 692 |
method |
| 693 |
</td> |
| 694 |
</tr> |
| 695 |
|
| 696 |
<tr class="alt"> |
| 697 |
<td><code>req.requestURL</code></td> |
| 698 |
<td> |
| 699 |
as returned by <a |
| 700 |
href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletRequest.html#getRequestURL%28%29">getRequestURL()</a> |
| 701 |
method |
| 702 |
</td> |
| 703 |
</tr> |
| 704 |
|
| 705 |
<tr> |
| 706 |
<td><code>req.queryString</code></td> |
| 707 |
<td> |
| 708 |
as returned by <a |
| 709 |
href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletRequest.html#getQueryString%28%29">getQueryString()</a> method |
| 710 |
</td> |
| 711 |
</tr> |
| 712 |
|
| 713 |
<tr class="alt"> |
| 714 |
<td><code>req.userAgent</code></td> |
| 715 |
<td>value of the "User-Agent" header |
| 716 |
</td> |
| 717 |
</tr> |
| 718 |
|
| 719 |
</table> |
| 720 |
|
| 721 |
<p>To install <code>MDCInsertingServletFilter</code> add the |
| 722 |
following lines to your web-application's <em>web.xml</em> file</p> |
| 723 |
|
| 724 |
<pre class="prettyprint source"><filter> |
| 725 |
<filter-name>MDCInsertingServletFilter</filter-name> |
| 726 |
<filter-class> |
| 727 |
ch.qos.logback.classic.helpers.MDCInsertingServletFilter |
| 728 |
</filter-class> |
| 729 |
</filter> |
| 730 |
<filter-mapping> |
| 731 |
<filter-name>MDCInsertingServletFilter</filter-name> |
| 732 |
<url-pattern>/*</url-pattern> |
| 733 |
</filter-mapping> </pre> |
| 734 |
|
| 735 |
<p><b>If your web-app has multiple filters, make sure that |
| 736 |
<code>MDCInsertingServletFilter</code> is declared before other |
| 737 |
filters.</b> For example, assuming the main processing in your |
| 738 |
web-app is done in filter 'F', the MDC values set by |
| 739 |
<code>MDCInsertingServletFilter</code> will not be seen by the code |
| 740 |
invoked by 'F' if <code>MDCInsertingServletFilter</code> comes after |
| 741 |
'F'. |
| 742 |
</p> |
| 743 |
|
| 744 |
<p>Once the filter is installed, values corresponding to each MDC |
| 745 |
key will be output by the %X <a |
| 746 |
href="layouts.html#conversionWord">conversion word</a> according to |
| 747 |
the key passes as first option. For example, to print the remote |
| 748 |
host followed by the request URI on one line, the date followed by |
| 749 |
the message on the next, you would set <code>PatternLayout</code>'s |
| 750 |
pattern to: |
| 751 |
|
| 752 |
</p> |
| 753 |
|
| 754 |
<p class="source">%X{req.remoteHost} %X{req.requestURI}%n%d - %m%n</p> |
| 755 |
|
| 756 |
<script src="../templates/footer.js" type="text/javascript"></script> |
| 757 |
</div> |
| 758 |
</body> |
| 759 |
</html> |