| 1 |
<html dir="ltr" xmlns="http://www.w3.org/1999/xhtml"> |
| 2 |
<head> |
| 3 |
<meta http-equiv="content-type" content="text/html; charset=UTF-8"></meta> |
| 4 |
<title>第8章 診断コンテキスト</title> |
| 5 |
<link rel="stylesheet" type="text/css" href="../css/common.css"></link> |
| 6 |
<link rel="stylesheet" type="text/css" href="../css/screen.css" media="screen"></link> |
| 7 |
<link rel="stylesheet" type="text/css" href="../css/_print.css" media="print"></link> |
| 8 |
<link rel="stylesheet" type="text/css" href="../css/prettify.css" media="screen"></link> |
| 9 |
</head> |
| 10 |
<body dir="ltr" onload="prettyPrint(); decorate();"> |
| 11 |
<script type="text/javascript">prefix='../';</script> |
| 12 |
<script type="text/javascript" src="../js/prettify.js"></script> |
| 13 |
<script src="../templates/header.js" type="text/javascript"></script> |
| 14 |
<script type="text/javascript" src="../js/dsl.js"></script> |
| 15 |
<script type="text/javascript" src="../js/jquery-min.js"></script> |
| 16 |
<script type="text/javascript" src="../js/decorator.js"></script> |
| 17 |
<div id="left"> |
| 18 |
<noscript>Please turn on Javascript to view this menu</noscript> |
| 19 |
<script src="../templates/left.js" type="text/javascript"></script> |
| 20 |
</div> |
| 21 |
<div id="right"> |
| 22 |
<script src="menu_ja.js" type="text/javascript"></script> |
| 23 |
</div> |
| 24 |
<div id="content"> |
| 25 |
|
| 26 |
<h1>第8章 診断コンテキスト</h1> |
| 27 |
|
| 28 |
<div class="quote"> |
| 29 |
<p><em>ドアを閉めなさい</em></p> |
| 30 |
<p>—LEROY CAIN, Flight Director, Columbia Mission Control</p> |
| 31 |
</div> |
| 32 |
|
| 33 |
<script src="../templates/creative.js" type="text/javascript"></script> |
| 34 |
|
| 35 |
<p>logbackの設計目標の1つとして、複雑な分散アプリケーションの監査とデバッグに使うことがあります。現実世界のほとんどの分散型システムは、同時に複数のクライアントの相手をしなければなりません。こういうシステムの典型的なマルチスレッドの実装は、スレッドが別々のクライアントを処理するものです。それぞれのクライアントに対するログ出力を分離するために実際に行われているアプローチは、クライアントごとに新しいロガーを用意するという少々残念なものです。このやり方ではやたらめったらロガーを生成することになりますし、管理のためのオーバーヘッドも馬鹿になりません。 |
| 36 |
</p> |
| 37 |
|
| 38 |
<script src="../templates/setup.js" type="text/javascript"></script> |
| 39 |
|
| 40 |
|
| 41 |
<p>もう少し軽めのやり方としては、リクエストを受け付けたクライアントの固有の情報をログに出力する方法があります。この方法は書籍「Patterns for Logging Diagnostic Messages in Pattern Languages of Program Design 3」(Addison-Wesley, 1997)でニール・ハリソンが紹介しています。logback が利用しているのはSLF4J API の診断コンテキスト(MDC)で、これはさっき紹介した技法を応用したものです。 |
| 42 |
</p> |
| 43 |
|
| 44 |
<p>リクエストごとの固有の情報として、利用者はコンテキストの情報を<code>MDC</code>(Mapped Diagnostic Contextの略です)に設定します。MDCクラスの特筆すべき部分を紹介します。メソッドの完全な説明は<a href="http://www.slf4j.org/api/org/slf4j/MDC.html">MDCのjavadoc</a>を参照してください。 |
| 45 |
</p> |
| 46 |
|
| 47 |
<pre class="prettyprint source">package org.slf4j; |
| 48 |
|
| 49 |
public class MDC { |
| 50 |
//Put a context value as identified by <em>key</em> |
| 51 |
//into the current thread's context map. |
| 52 |
<b>public static void put(String key, String val);</b> |
| 53 |
|
| 54 |
//Get the context identified by the <code>key</code> parameter. |
| 55 |
<b>public static String get(String key);</b> |
| 56 |
|
| 57 |
//Remove the context identified by the <code>key</code> parameter. |
| 58 |
<b>public static void remove(String key);</b> |
| 59 |
|
| 60 |
//Clear all entries in the MDC. |
| 61 |
<b>public static void clear();</b> |
| 62 |
}</pre> |
| 63 |
|
| 64 |
<p><code>MDC</code>クラスには静的メソッドしかありません。おかげで、開発者が<em>診断コンテキスト</em>に設定した情報は、logback のありとあらゆるコンポーネントから取得できるようになるのです。<code>MDC</code>はコンテキストの情報を<em>スレッドごとに</em>管理します。子スレッドは、親の診断コンテキストの<em>コピー</em>を自動的に継承します。普通なら、開発者はクライアントから受け付けた新しい要求の処理を始めるところで、クライアント識別子、IPアドレス、リクエストパラメーターなどの適切なコンテキスト情報を<code>MDC</code>に設定します。logback のコンポーネントがちゃんと設定されていれば、こういった情報は自動的にログ項目に含まれるようになります。 |
| 65 |
</p> |
| 66 |
|
| 67 |
<p>logback-classic の MDC 実装は、値の書き込みが比較的穏やかに行われることを想定しているのでくれぐれも注意してください。</p> |
| 68 |
|
| 69 |
<p><code><a href="http://logback.qos.ch/xref/chapters/mdc/SimpleMDC.html">SimpleMDC</a></code>アプリケーションを使ってこの基本原則を説明しましょう。 |
| 70 |
</p> |
| 71 |
<p class="example">例7.1:MDCの基本的な使い方(<a href="http://logback.qos.ch/xref/chapters/mdc/SimpleMDC.html">logback-examples/src/main/java/chapters/mdc/SimpleMDC.java</a>)</p> |
| 72 |
<pre class="prettyprint source">package chapters.mdc; |
| 73 |
|
| 74 |
import org.slf4j.Logger; |
| 75 |
import org.slf4j.LoggerFactory; |
| 76 |
import org.slf4j.MDC; |
| 77 |
|
| 78 |
import ch.qos.logback.classic.PatternLayout; |
| 79 |
import ch.qos.logback.core.ConsoleAppender; |
| 80 |
|
| 81 |
public class SimpleMDC { |
| 82 |
static public void main(String[] args) throws Exception { |
| 83 |
|
| 84 |
// You can put values in the MDC at any time. Before anything else |
| 85 |
// we put the first name |
| 86 |
MDC.put("first", "Dorothy"); |
| 87 |
|
| 88 |
[ SNIP ] |
| 89 |
|
| 90 |
Logger logger = LoggerFactory.getLogger(SimpleMDC.class); |
| 91 |
// We now put the last name |
| 92 |
MDC.put("last", "Parker"); |
| 93 |
|
| 94 |
// The most beautiful two words in the English language according |
| 95 |
// to Dorothy Parker: |
| 96 |
logger.info("Check enclosed."); |
| 97 |
logger.debug("The most beautiful two words in English."); |
| 98 |
|
| 99 |
MDC.put("first", "Richard"); |
| 100 |
MDC.put("last", "Nixon"); |
| 101 |
logger.info("I am not a crook."); |
| 102 |
logger.info("Attributed to the former US president. 17 Nov 1973."); |
| 103 |
} |
| 104 |
|
| 105 |
[ SNIP ] |
| 106 |
|
| 107 |
}</pre> |
| 108 |
|
| 109 |
<p>mainメソッドでは、まずキー<em>first</em>で値<em>Drothy</em>を<code>MDC</code>に設定します。<code>MDC</code>に指定するキーも値も利用者の自由です。同じキーで書き込むと前の値を上書きします。コード上ではlogbackの設定が行われているところです。</p> |
| 110 |
|
| 111 |
<p>簡潔にするため、logbackを<a href="http://github.com/qos-ch/logback/blob/master/logback-examples/src/main/java/chapters/mdc/simpleMDC.xml">simpleMDC.xml</a>で設定しているところは省略しました。設定ファイル中の該当する箇所は次のようになっています。 |
| 112 |
</p> |
| 113 |
|
| 114 |
<pre class="prettyprint source"><appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> |
| 115 |
<layout> |
| 116 |
<Pattern><b>%X{first} %X{last}</b> - %m%n</Pattern> |
| 117 |
</layout> |
| 118 |
</appender></pre> |
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
<p><code>PatternLayout</code>の変換パターン文字列中の<em>%X変換指定子</em>の使い方を見てください。<em>%X変換指定子</em>二回登場しています。一つ目のキーには<em>first</em>、二つ目のキーには<em>last</em>を指定しています。<code>SimpleMDC.class</code>のロガーを取得した後で、MDCにキー<em>last</em>で値<em>Parker</em>を設定しています。それから、メッセージを変えて二回ロギング要求を発行しています。最後に、また別の値を<code>MDC</code>に設定してから、いくつかロギング要求を発行しています。SimpleMDCを実行すると次のような出力になります。</p> |
| 123 |
|
| 124 |
<div class="source"><pre>Dorothy Parker - Check enclosed. |
| 125 |
Dorothy Parker - The most beautiful two words in English. |
| 126 |
Richard Nixon - I am not a crook. |
| 127 |
Richard Nixon - Attributed to the former US president. 17 Nov 1973.</pre></div> |
| 128 |
|
| 129 |
|
| 130 |
<p><code>SimpleMDC</code>アプリケーションを見れば、logbackを適切に設定すると、<code>MDC</code>の値がどのようにレイアウトされて出力されるのかがわかります。また、<code>MDC</code>に設定された情報はロガーの呼び出し一度だけでなく、何度も利用できることがわかります。 |
| 131 |
</p> |
| 132 |
|
| 133 |
<h3 class="doAnchor">応用</h3> |
| 134 |
|
| 135 |
<p>診断コンテキストが一番脚光を浴びるのはクライアント・サーバーアーキテクチャだ。一般的に、複数のクライアントはサーバ上の複数のスレッドで処理されます。しかし<code>MDC</code>クラスには静的メソッドしかないので、診断コンテキストはスレッドごとに管理するしかありません。つまり、サーバー上のスレッドそれぞれが<code>MDC</code>の分のコストを負うことになるのです。<code>MDC</code>の<code>put()</code>や<code>get()</code>ような操作は、<em>現在の</em>スレッドと子スレッドの<code>MDC</code>にしか影響しません。他のスレッドの<code>MDC</code>は影響を受けないのです。<code>MDC</code>の情報はスレッドごとに管理されているので、それぞれのスレッドは自分用の<code>MDC</code>を持っていることになります。したがって、開発者はスレッド安全性やスレッド間同期のことを考える必要はありません。<code>MDC</code>はそういったことを安全に、透過的に扱えるのです。 |
| 136 |
</p> |
| 137 |
|
| 138 |
<p>次の例は少し凝っています。クライアント・サーバ環境でどのように<code>MDC</code>を使うのか説明したものです。サーバーは例7.2の<code>NumberCrucher</code>インターフェイスを実装します。<code>The NumberCruncher</code>インターフェイスには、<code>factor()</code>というメソッドが1つあるだけです。クライアントは、RMIによってサーバアプリケーションの<code>factor()</code>メソッドを呼び出して、指定した整数の素因数を取得します。 |
| 139 |
</p> |
| 140 |
|
| 141 |
<p class="example">例7.2:サービスインターフェイス(<a href="http://logback.qos.ch/xref/chapters/mdc/NumberCruncher.html">logback-examples/src/main/java/chapters/mdc/NumberCruncher.java</a>)</p> |
| 142 |
|
| 143 |
<pre class="prettyprint source">package chapters.mdc; |
| 144 |
|
| 145 |
import java.rmi.Remote; |
| 146 |
import java.rmi.RemoteException; |
| 147 |
|
| 148 |
/** |
| 149 |
* NumberCruncher factors positive integers. |
| 150 |
*/ |
| 151 |
public interface NumberCruncher extends Remote { |
| 152 |
/** |
| 153 |
* Factor a positive integer <code>number</code> and return its |
| 154 |
* <em>distinct</em> factor's as an integer array. |
| 155 |
* */ |
| 156 |
int[] factor(int number) throws RemoteException; |
| 157 |
}</pre> |
| 158 |
|
| 159 |
<p>例7.3の<code>NumberCruncherServer</code>アプリケーションが<code>NumberCruncher</code>インターフェイスを実装しています。mainメソッドはlocalhost上でRMIレジストリを公開して、well-knownポートでリクエストを待ち受けます。 |
| 160 |
</p> |
| 161 |
|
| 162 |
<p class="example">例7.3:サーバー実装(<a href="http://logback.qos.ch/xref/chapters/mdc/NumberCruncherServer.html">logback-examples/src/main/java/chapters/mdc/NumberCruncherServer.java</a>)</p> |
| 163 |
|
| 164 |
<pre class="prettyprint source">package chapters.mdc; |
| 165 |
|
| 166 |
import java.rmi.RemoteException; |
| 167 |
import java.rmi.registry.LocateRegistry; |
| 168 |
import java.rmi.registry.Registry; |
| 169 |
import java.rmi.server.UnicastRemoteObject; |
| 170 |
import java.util.Vector; |
| 171 |
|
| 172 |
import org.slf4j.Logger; |
| 173 |
import org.slf4j.LoggerFactory; |
| 174 |
import org.slf4j.MDC; |
| 175 |
|
| 176 |
import ch.qos.logback.classic.LoggerContext; |
| 177 |
import ch.qos.logback.classic.joran.JoranConfigurator; |
| 178 |
import ch.qos.logback.core.joran.spi.JoranException; |
| 179 |
|
| 180 |
|
| 181 |
/** |
| 182 |
* A simple NumberCruncher implementation that logs its progress when |
| 183 |
* factoring numbers. The purpose of the whole exercise is to show the |
| 184 |
* use of mapped diagnostic contexts in order to distinguish the log |
| 185 |
* output from different client requests. |
| 186 |
* */ |
| 187 |
public class NumberCruncherServer extends UnicastRemoteObject |
| 188 |
implements NumberCruncher { |
| 189 |
|
| 190 |
private static final long serialVersionUID = 1L; |
| 191 |
|
| 192 |
static Logger logger = LoggerFactory.getLogger(NumberCruncherServer.class); |
| 193 |
|
| 194 |
public NumberCruncherServer() throws RemoteException { |
| 195 |
} |
| 196 |
|
| 197 |
public int[] factor(int number) throws RemoteException { |
| 198 |
// The client's host is an important source of information. |
| 199 |
try { |
| 200 |
<b>MDC.put("client", NumberCruncherServer.getClientHost());</b> |
| 201 |
} catch (java.rmi.server.ServerNotActiveException e) { |
| 202 |
logger.warn("Caught unexpected ServerNotActiveException.", e); |
| 203 |
} |
| 204 |
|
| 205 |
// The information contained within the request is another source |
| 206 |
// of distinctive information. It might reveal the users name, |
| 207 |
// date of request, request ID etc. In servlet type environments, |
| 208 |
// useful information is contained in the HttpRequest or in the |
| 209 |
// HttpSession. |
| 210 |
<b>MDC.put("number", String.valueOf(number));</b> |
| 211 |
|
| 212 |
logger.info("Beginning to factor."); |
| 213 |
|
| 214 |
if (number <= 0) { |
| 215 |
throw new IllegalArgumentException(number + |
| 216 |
" is not a positive integer."); |
| 217 |
} else if (number == 1) { |
| 218 |
return new int[] { 1 }; |
| 219 |
} |
| 220 |
|
| 221 |
Vector<Integer> factors = new Vector<Integer>(); |
| 222 |
int n = number; |
| 223 |
|
| 224 |
for (int i = 2; (i <= n) && ((i * i) <= number); i++) { |
| 225 |
// It is bad practice to place log requests within tight loops. |
| 226 |
// It is done here to show interleaved log output from |
| 227 |
// different requests. |
| 228 |
logger.debug("Trying " + i + " as a factor."); |
| 229 |
|
| 230 |
if ((n % i) == 0) { |
| 231 |
logger.info("Found factor " + i); |
| 232 |
factors.addElement(new Integer(i)); |
| 233 |
|
| 234 |
do { |
| 235 |
n /= i; |
| 236 |
} while ((n % i) == 0); |
| 237 |
} |
| 238 |
|
| 239 |
// Placing artificial delays in tight loops will also lead to |
| 240 |
// sub-optimal results. :-) |
| 241 |
delay(100); |
| 242 |
} |
| 243 |
|
| 244 |
if (n != 1) { |
| 245 |
logger.info("Found factor " + n); |
| 246 |
factors.addElement(new Integer(n)); |
| 247 |
} |
| 248 |
|
| 249 |
int len = factors.size(); |
| 250 |
|
| 251 |
int[] result = new int[len]; |
| 252 |
|
| 253 |
for (int i = 0; i < len; i++) { |
| 254 |
result[i] = ((Integer) factors.elementAt(i)).intValue(); |
| 255 |
} |
| 256 |
|
| 257 |
<b>// clean up |
| 258 |
MDC.remove("client"); |
| 259 |
MDC.remove("number");</b> |
| 260 |
|
| 261 |
return result; |
| 262 |
} |
| 263 |
|
| 264 |
static void usage(String msg) { |
| 265 |
System.err.println(msg); |
| 266 |
System.err.println("Usage: java chapters.mdc.NumberCruncherServer configFile\n" + |
| 267 |
" where configFile is a logback configuration file."); |
| 268 |
System.exit(1); |
| 269 |
} |
| 270 |
|
| 271 |
public static void delay(int millis) { |
| 272 |
try { |
| 273 |
Thread.sleep(millis); |
| 274 |
} catch (InterruptedException e) { |
| 275 |
} |
| 276 |
} |
| 277 |
|
| 278 |
public static void main(String[] args) { |
| 279 |
if (args.length != 1) { |
| 280 |
usage("Wrong number of arguments."); |
| 281 |
} |
| 282 |
|
| 283 |
String configFile = args[0]; |
| 284 |
|
| 285 |
if (configFile.endsWith(".xml")) { |
| 286 |
try { |
| 287 |
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); |
| 288 |
JoranConfigurator configurator = new JoranConfigurator(); |
| 289 |
configurator.setContext(lc); |
| 290 |
lc.reset(); |
| 291 |
configurator.doConfigure(args[0]); |
| 292 |
} catch (JoranException je) { |
| 293 |
je.printStackTrace(); |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
NumberCruncherServer ncs; |
| 298 |
|
| 299 |
try { |
| 300 |
ncs = new NumberCruncherServer(); |
| 301 |
logger.info("Creating registry."); |
| 302 |
|
| 303 |
Registry registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT); |
| 304 |
registry.rebind("Factor", ncs); |
| 305 |
logger.info("NumberCruncherServer bound and ready."); |
| 306 |
} catch (Exception e) { |
| 307 |
logger.error("Could not bind NumberCruncherServer.", e); |
| 308 |
|
| 309 |
return; |
| 310 |
} |
| 311 |
} |
| 312 |
}</pre> |
| 313 |
|
| 314 |
<p>特に大事なのが<code>factor(int number)</code>メソッドの実装です。最初に、<code>MDC</code>へキー<em>client</em>でクライアントのホスト名を設定しています。そして、クライアントから渡された素因数分解する数をキー<em>number</em>で<code>MDC</code>に設定します。計算が終わったらクライアントに結果を返します。ですが、結果を返す前に、キー<em>client</em>とキー<em>number</em>で設定された値をクリアするため、<code>MDC.remove()</code>メソッドを呼んでいます。普通なら<code>put()</code>操作と<code>remove()</code>操作が同じ数だけ登場するべきです。そうしないと、<code>MDC</code>に特定のキーの値が残ってしまうからです。出来る限り<code>remove()</code>操作をfinallyブロックで実行するように仕込んでおくことをおすすめします。確実に実行されることを保証するためです。 |
| 315 |
</p> |
| 316 |
|
| 317 |
<p>理屈っぽい説明が続きましたが、cruncer アプリケーションを実行する準備が整いました。次のコマンドを実行してサーバーを起動しましょう。</p> |
| 318 |
|
| 319 |
<div class="source"><pre>java chapters.mdc.NumberCruncherServer src/main/java/chapters/mdc/mdc1.xml</pre></div> |
| 320 |
|
| 321 |
<p><em>mdc1.xml</em>の内容は次のとおりです。</p> |
| 322 |
|
| 323 |
<p class="example">例7.4:設定ファイル(<a href="http://logback.qos.ch/xref/chapters/mdc/mdc1.xml">logback-examples/src/main/java/chapters/mdc/mdc1.xml</a>)</p> |
| 324 |
|
| 325 |
<pre class="prettyprint source"><configuration> |
| 326 |
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> |
| 327 |
<layout> |
| 328 |
<Pattern>%-4r [%thread] %-5level <b>C:%X{client} N:%X{number}</b> - %msg%n</Pattern> |
| 329 |
</layout> |
| 330 |
</appender> |
| 331 |
|
| 332 |
<root level="debug"> |
| 333 |
<appender-ref ref="CONSOLE"/> |
| 334 |
</root> |
| 335 |
</configuration></pre> |
| 336 |
|
| 337 |
<p><span class="option">パターン·</span>オプションに<em>%X変換指定子</em>が使われているのを見てください。 |
| 338 |
</p> |
| 339 |
|
| 340 |
<p>次のコマンドで<code>NumberCruncherClient</code>アプリケーションを実行しましょう。</p> |
| 341 |
|
| 342 |
<div class="source"><pre>java chapters.mdc.NumberCruncherClient <em>hostname</em></pre></div> |
| 343 |
|
| 344 |
<p><em>hostname</em>の部分には<code>NumberCruncherServer</code>を実行しているサーバのホスト名を指定します。</p> |
| 345 |
|
| 346 |
<p>複数のクライアントを実行して、最初に起動したクライアントがサーバに129を要求して、その後すぐに二つ目のクライアントから71を要求したときのサーバ側のコンソールには、次のように出力されています。</p> |
| 347 |
|
| 348 |
<div class="source"><pre> |
| 349 |
<b>70984 [RMI TCP Connection(4)-192.168.1.6] INFO C:orion N:129 - Beginning to factor.</b> |
| 350 |
70984 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 2 as a factor. |
| 351 |
71093 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 3 as a factor. |
| 352 |
71093 [RMI TCP Connection(4)-192.168.1.6] INFO C:orion N:129 - Found factor 3 |
| 353 |
71187 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 4 as a factor. |
| 354 |
71297 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 5 as a factor. |
| 355 |
71390 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 6 as a factor. |
| 356 |
<b>71453 [RMI TCP Connection(5)-192.168.1.6] INFO C:orion N:71 - Beginning to factor.</b> |
| 357 |
71453 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 2 as a factor. |
| 358 |
71484 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 7 as a factor. |
| 359 |
71547 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 3 as a factor. |
| 360 |
71593 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 8 as a factor. |
| 361 |
71656 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 4 as a factor. |
| 362 |
71687 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 9 as a factor. |
| 363 |
71750 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 5 as a factor. |
| 364 |
71797 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 10 as a factor. |
| 365 |
71859 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 6 as a factor. |
| 366 |
71890 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 11 as a factor. |
| 367 |
71953 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 7 as a factor. |
| 368 |
72000 [RMI TCP Connection(4)-192.168.1.6] INFO C:orion N:129 - Found factor 43 |
| 369 |
72062 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 8 as a factor. |
| 370 |
72156 [RMI TCP Connection(5)-192.168.1.6] INFO C:orion N:71 - Found factor 71</pre></div> |
| 371 |
|
| 372 |
<p>クライアントは<em>orion</em>というホスト名のマシンで実行されていることがわかります。サーバーがほぼ同時に別のスレッドでクライアントの要求を処理する場合でも、それぞれのクライアントからのリクエストによるログ出力は、<code>MDC</code>の出力を見れば分かるようになっています。たとえば、<em>number</em>として印付けられた素因数分解する数です。 |
| 373 |
</p> |
| 374 |
|
| 375 |
<p>注意深い人なら、スレッド名を見るだけでもリクエストを区別できることが分かるでしょう。サーバ側の実装がスレッドを再利用するようになっていると混乱させられるかもしれません。そうなってしまったら、いつリクエストを受け付けて、いつ応答を返したのかを特定するのは難しいかもしれません。<code>MDC</code>を管理するのはアプリケーション開発者なので、そういった問題が起きることはありません。 |
| 376 |
</p> |
| 377 |
|
| 378 |
|
| 379 |
|
| 380 |
<h3 class="doAnchor" name="autoMDC"><code>MDC</code>への自動的なアクセス</h3> |
| 381 |
|
| 382 |
<p>これまでに見てきたように、<code>MDC</code>があると複数のクライアントの相手をするとき便利です。ユーザー認証のあるWebアプリケーションなら、<code>MDC</code>にユーザー名を設定して、ログアウトするときにそれを削除するようにしておくのが、1つの簡単なソリューションになるでしょう。残念ながら、そのテクニックを使っていても常に確実な結果を得られるわけではありません。<code>MDC</code>がスレッド毎にデータを管理している限り、サーバがスレッドをリサイクするようになっていると、間違った情報が設定されていることがあるかもしれません。</p> |
| 383 |
|
| 384 |
<p>リクエストを処理するとき、いつでも<code>MDC</code>に正しい情報が設定されていることを確実にするためにできるのは、処理の始めにユーザー名を設定して、処理の終わりに削除することです。こういう場合サーブレット<code><a href="http://java.sun.com/javaee/5/docs/api/javax/servlet/Filter.html">Filter</a></code>を使うとよいでしょう。 |
| 385 |
</p> |
| 386 |
|
| 387 |
<p>サーブレットフィルターの<code>doFilter()</code>メソッドで、リクエストに関連する情報(cookieも)を集めて、それを<code>MDC</code>に設定するのです。他のフィルターで行う後続処理やサーブレットからは、自動的に今設定したばかりのMDCの情報を参照することができます。最後にまたサーブレットフィルターが仕事をするとき、MDCに設定した内容を削除することができます。 |
| 388 |
</p> |
| 389 |
|
| 390 |
<p>フィルターの実装例を見てみましょう。</p> |
| 391 |
|
| 392 |
<p class="example">例7.5:ユーザー名サーブレットフィルター(<a href="http://logback.qos.ch/xref/chapters/mdc/UserServletFilter.html">logback-examples/src/main/java/chapters/mdc/UserServletFilter.html</a>)</p> |
| 393 |
|
| 394 |
<pre class="prettyprint source">package chapters.mdc; |
| 395 |
|
| 396 |
import java.io.IOException; |
| 397 |
import java.security.Principal; |
| 398 |
|
| 399 |
import javax.servlet.Filter; |
| 400 |
import javax.servlet.FilterChain; |
| 401 |
import javax.servlet.FilterConfig; |
| 402 |
import javax.servlet.ServletException; |
| 403 |
import javax.servlet.ServletRequest; |
| 404 |
import javax.servlet.ServletResponse; |
| 405 |
import javax.servlet.http.HttpServletRequest; |
| 406 |
import javax.servlet.http.HttpSession; |
| 407 |
|
| 408 |
import org.slf4j.MDC; |
| 409 |
|
| 410 |
public class UserServletFilter implements Filter { |
| 411 |
|
| 412 |
private final String USER_KEY = "username"; |
| 413 |
|
| 414 |
public void destroy() { |
| 415 |
} |
| 416 |
|
| 417 |
public void doFilter(ServletRequest request, ServletResponse response, |
| 418 |
FilterChain chain) throws IOException, ServletException { |
| 419 |
|
| 420 |
boolean successfulRegistration = false; |
| 421 |
|
| 422 |
HttpServletRequest req = (HttpServletRequest) request; |
| 423 |
Principal principal = req.getUserPrincipal(); |
| 424 |
// Please note that we could have also used a cookie to |
| 425 |
// retrieve the user name |
| 426 |
|
| 427 |
if (principal != null) { |
| 428 |
String username = principal.getName(); |
| 429 |
successfulRegistration = registerUsername(username); |
| 430 |
} |
| 431 |
|
| 432 |
try { |
| 433 |
chain.doFilter(request, response); |
| 434 |
} finally { |
| 435 |
if (successfulRegistration) { |
| 436 |
MDC.remove(USER_KEY); |
| 437 |
} |
| 438 |
} |
| 439 |
} |
| 440 |
|
| 441 |
public void init(FilterConfig arg0) throws ServletException { |
| 442 |
} |
| 443 |
|
| 444 |
|
| 445 |
/** |
| 446 |
* Register the user in the MDC under USER_KEY. |
| 447 |
* |
| 448 |
* @param username |
| 449 |
* @return true id the user can be successfully registered |
| 450 |
*/ |
| 451 |
private boolean registerUsername(String username) { |
| 452 |
if (username != null && username.trim().length() > 0) { |
| 453 |
MDC.put(USER_KEY, username); |
| 454 |
return true; |
| 455 |
} |
| 456 |
return false; |
| 457 |
} |
| 458 |
}</pre> |
| 459 |
|
| 460 |
<p><code>doFilter()</code>メソッドが呼ばれたら、最初にリクエストオブジェクトから<code>java.security.Principal</code>オブジェクトを取得します。このオブジェクトからは、現在認証されているユーザーのユーザー名を取得することができます。ユーザー情報があったらそれを<code>MDC</code>に設定します。</p> |
| 461 |
|
| 462 |
<p>フィルターチェインが完了すると、フィルターでは<code>MDC</code>からユーザー情報を削除します。</p> |
| 463 |
|
| 464 |
<p>ここで紹介したやり方は、スレッドがリクエストを処理している間だけMDCに値を設定するものです。他のスレッドは影響を受けません。さらに、あらゆるスレッドが、任意の時点で正確なMDCデータを持つようになります。</p> |
| 465 |
|
| 466 |
|
| 467 |
|
| 468 |
<h3 class="doAnchor" name="managedThreads">MDCおよび管理スレッド</h3> |
| 469 |
|
| 470 |
<p>ワーカースレッドが自身を初期化するとき、どんなときでも診断コンテキストを継承するわけではありません。これは<code>java.util.concurrent.Executors</code>がスレッドを管理しているときに発生します。例えば、 <code>newCachedThreadPool</code>は<code>ThreadPoolExecutor</code>オブジェクトを作成しますが、他のスレッドプールを生成するコードでも、スレッドの生成は複雑なロジックになっています。 |
| 471 |
</p> |
| 472 |
|
| 473 |
<p>そういう場合、元のスレッド(master)でタスクをエグゼキューターに渡す前に、<code>MDC.getCopyOfContextMap()</code>メソッドを呼ぶようにするとよいでしょう。タスクが実行されるとき、まず最初に<code>MDC.setContextMapValues()</code>メソッドを呼ぶようにするべきです。そうすると新しい<code>Executor</code>のスレッドに、元のMDCの値を関連付けることができます。 |
| 474 |
</p> |
| 475 |
|
| 476 |
<h3 class="doAnchor" name="mis">MDCInsertingServletFilter</h3> |
| 477 |
|
| 478 |
<p>Webアプリケーションでは、受け付けたHTTPリクエストに関連するホスト名、リクエストURI、ユーザーエージェント文字列などがわかるようになっていると便利なのはよくご存知だと思います。<a href="http://logback.qos.ch/xref/ch/qos/logback/classic/helpers/MDCInsertingServletFilter.html"><code>MDCInsertingServletFilter</code></a>はMDCに次のようなキーと値を設定します。 |
| 479 |
</p> |
| 480 |
|
| 481 |
<table class="bodyTable"> |
| 482 |
<tr> |
| 483 |
<th>キー</th> |
| 484 |
<th>値</th> |
| 485 |
</tr> |
| 486 |
|
| 487 |
<tr class="alt"> |
| 488 |
<td><code>req.remoteHost</code></td> |
| 489 |
<td><a href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletRequest.html#getRemoteHost%28%29">getRemoteHost()</a>メソッドの返すホスト名</td> |
| 490 |
</tr> |
| 491 |
|
| 492 |
<tr> |
| 493 |
<td><code>req.xForwardedFor</code></td> |
| 494 |
<td><a href="http://en.wikipedia.org/wiki/X-Forwarded-For">"X-Forwarded-For"</a>ヘッダーの値</td> |
| 495 |
</tr> |
| 496 |
|
| 497 |
<tr class="alt"> |
| 498 |
<td><code>req.requestURI</code></td> |
| 499 |
<td><a href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletRequest.html#getRequestURI%28%29">getRequestURI()</a>メソッドの返すリクエストURI</td> |
| 500 |
</tr> |
| 501 |
|
| 502 |
<tr> |
| 503 |
<td><code>req.requestURL</code></td> |
| 504 |
<td><a href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletRequest.html#getRequestURL%28%29">getRequestURL()</a>メソッドの返すリクエストURL</td> |
| 505 |
</tr> |
| 506 |
|
| 507 |
<tr class="alt"> |
| 508 |
<td><code>req.queryString</code></td> |
| 509 |
<td><a href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletRequest.html#getQueryString%28%29">getQueryString()</a>メソッドの返すクエリ文字列</td> |
| 510 |
</tr> |
| 511 |
|
| 512 |
<tr> |
| 513 |
<td><code>req.userAgent</code></td> |
| 514 |
<td>"User-Agent" ヘッダーの値</td> |
| 515 |
</tr> |
| 516 |
|
| 517 |
</table> |
| 518 |
|
| 519 |
<p><code>MDCInsertingServletFilter</code>を使用するには、Webアプリケーションの<em>web.xml</em>に次の設定を追加します。</p> |
| 520 |
|
| 521 |
<pre class="prettyprint source"><filter> |
| 522 |
<filter-name>MDCInsertingServletFilter</filter-name> |
| 523 |
<filter-class> |
| 524 |
ch.qos.logback.classic.helpers.MDCInsertingServletFilter |
| 525 |
</filter-class> |
| 526 |
</filter> |
| 527 |
<filter-mapping> |
| 528 |
<filter-name>MDCInsertingServletFilter</filter-name> |
| 529 |
<url-pattern>/*</url-pattern> |
| 530 |
</filter-mapping> </pre> |
| 531 |
|
| 532 |
<p><b>複数のフィルターを使用している場合、<code>MDCInsertingServletFilter</code>を他のフィルターより先に宣言するようにしてください。</b> たとえば、アプリケーションの主な処理がフィルター'F'で行われるとしたら、その前に<code>MDCInsertingServletFilter</code>を置かないと、MDCに設定される値を'F'から参照することはできません。 |
| 533 |
</p> |
| 534 |
|
| 535 |
<p>フィルターを配置したら、上記のMDCのキーを%X変換指定子で使えるようになります。例えば、リモートホストとリクエストURIを一行に出したければ、次のような変換パターン文字列を指定すればよいでしょう。</p> |
| 536 |
|
| 537 |
<p class="source">%X{req.remoteHost} %X{req.requestURI}%n%d - %m%n</p> |
| 538 |
|
| 539 |
<script src="../templates/footer.js" type="text/javascript"></script> |
| 540 |
</div> |
| 541 |
</body> |
| 542 |
</html> |