Debian Codegraph @

logback-site/src/site/pages/recipes/emailPerTransaction.html

raw
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>Email per transaction</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
13 </head>
14 <body onload="prettyPrint()">
15 <script type="text/javascript">prefix='../';</script>
16 <script type="text/javascript" src="../js/prettify.js"></script>
17 <script src="../templates/header.js" type="text/javascript"></script>
18 <div id="left">
19 <noscript>Please turn on Javascript to view this menu</noscript>
20 <script src="../templates/left.js" type="text/javascript"></script>
21 </div>
22 <div id="content">
23
24 <h2>Triggering an email containing the isolated logs of selected
25 transactions</h2>
26
27 <p>Let Dave and Carol be software QA engineers working at a
28 company called Fooware.com. As you might have guessed,
29 Fooware.com sells foos. Yes, foos... Let <em>Buscrit</em> be a
30 business critical backend system running at Fooware.com. Buscrit
31 is called by a number of applications to make business-critical
32 transactions of various types.
33 </p>
34
35 <p>We would like to allow Carol to access the logging data
36 generated by Buscrit as conveniently as possible. We could
37 assume that Carol has access the log files directly on the
38 server where Buscrit runs. However, let us assume that accessing
39 the log files is somehow impractical because one or ore more of
40 the following conditions holds true:
41 </p>
42
43 <ol>
44 <li>Buscrit runs on multiple hosts and it is difficult to
45 identify the host where a particular transaction was
46 executed</li>
47 <li>Carol does not (or does not wish to) have access to the
48 hosts where Buscrit runs
49 </li>
50 <li>Buscrit is tested by multiple testers, e.g. Dave and Carol
51 and others, simultaneously so that it is hard to identify and
52 track an individual transaction in the log files
53 </li>
54 </ol>
55
56 <p>Given the above circumstances, let us create a logback
57 configuration so that Carol receives an email message at the end
58 of every transaction. We will iteratively refine this
59 configuration so that Carol will receive an email containing the
60 logs of each transaction in isolation and only for the
61 transactions she explicitly selects.
62 </p>
63
64 <h3>Triggering an email message at the end of each transaction</h3>
65
66 <p>We will be using <code>SMTPAppender</code> to generate emails
67 containing logging data. Please refer to the <a
68 href="../manual/appenders.html#SMTPAppender">appropriate section
69 of the manual</a> to familiarize yourself with
70 <code>SMTPAppender</code> and its properties.
71 </p>
72
73 <p>The <a href="demo.html">logback-demo</a> project contains a
74 Struts action called <a
75 href="http://logback-demo.qos.ch/xref/ch/qos/logback/demo/prime/PrimeAction.html"><code>PrimeAction</code></a>. It
76 can factorize integers. Here is the pertinent structure of
77 <code>PrimeAction</code>'s code:</p>
78
79 <pre class="prettyprint source">package ch.qos.logback.demo.prime;
80
81 import org.apache.struts.action.Action;
82 ...
83 import javax.servlet.http.HttpServletRequest;
84 import javax.servlet.http.HttpServletResponse;
85
86 public class PrimeAction extends Action {
87
88 Logger logger = LoggerFactory.getLogger(PrimeAction.class);
89 static Marker SMTP_TRIGGER = MarkerFactory.getMarker("SMTP_TRIGGER");
90
91 public ActionForward execute(ActionMapping actionMapping,
92 ActionForm actionForm, HttpServletRequest request,
93 HttpServletResponse response) throws Exception {
94
95 PrimeForm form = (PrimeForm) actionForm;
96
97 Long number = form.getNumber();
98 try {
99 NumberCruncher nc = new NumberCruncherImpl();
100 Long start = System.currentTimeMillis();
101 Long[] result = nc.factor(number);
102 Long duration = System.currentTimeMillis() - start;
103 logger.info("Results computed in {} ms", duration);
104
105 ...
106 } finally {
107 <b>logger.info(SMTP_TRIGGER, "Prime computation ended");</b>
108 }
109 }
110 } </pre>
111
112 <p>In a real world application, a transaction would involve
113 systems external to the application, e.g. a database or a
114 messaging queue. For the sake of this example, let us consider
115 each factorization request as a <em>transaction</em>. At the
116 end of each factorization request, i.e. each transaction, the
117 logger of the <code>PrimeAction</code> instance is invoked with
118 the SMTP_TRIGGER marker and the message "Prime computation
119 ended". We can capitalize on this logging request to clearly
120 identify the end of every transaction in order to trigger an
121 outgoing email message.
122 </p>
123
124 <p>Here is a configuration file which uses
125 <code>JaninoEventEvaluator</code> to trigger an outgoing email
126 for logging event marked with SMTP_TRIGGER.
127 </p>
128
129 <pre class="prettyprint
130 source">&lt;configuration scan="true" scanPeriod="3 seconds">
131
132 &lt;!-- always a good idea to have an OnConsoleStatusListener -->
133 &lt;statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" />
134
135 &lt;appender name="SMTP" class="ch.qos.logback.classic.net.SMTPAppender">
136 &lt;smtpHost>NAME_OF_SMTP_HOST&lt;/smtpHost>
137 &lt;to>...&lt;/to>
138 &lt;from>...&lt;/from>
139 &lt;subject>Prime - %mdc{number} by %mdc{userid} &lt;/subject>
140 &lt;layout class="ch.qos.logback.classic.html.HTMLLayout">
141 &lt;pattern>%date%level%logger{24}%msg&lt;/pattern>
142 &lt;/layout>
143
144 <b>&lt;evaluator class="ch.qos.logback.classic.boolex.JaninoEventEvaluator"></b>
145 <b>&lt;expression></b>
146 <b>marker != null &amp;&amp; marker.contains("SMTP_TRIGGER")</b>
147 <b>&lt;/expression></b>
148 <b>&lt;/evaluator></b>
149 &lt;/appender>
150
151 &lt;root level="DEBUG">
152 &lt;appender-ref ref="SMTP" />
153 &lt;/root>
154
155 &lt;/configuration></pre>
156
157
158
159 <h3>Transaction isolation</h3>
160
161 <p>While the previous configuration file will trigger an outgoing
162 email message whenever an event is marked with "SMTP_TRIGGER", the
163 contents of the message will contain events generated by different
164 transactions. With a little effort, we can actually separate events
165 belonging to different transactions so that the outgoing email
166 triggered at the end of the transaction contains logs from that
167 transaction and only that transaction.
168 </p>
169
170 <p>To isolate a given transaction, there must first be a way to
171 distinguish it from other transactions. Typically this would be
172 accomplished by putting the unique identifier of the transaction
173 into the MDC.
174 </p>
175
176 <pre class="prettyprint source">String transactionId = ...; // extract id from transaction
177 MDC.put("txId", transactionId); </pre>
178
179 <p>In the <a
180 href="http://logback-demo.qos.ch/xref/ch/qos/logback/demo/UserServletFilter.html"><code>UserServletFilter</code></a>
181 class, this is done by retrieving the id of the session and putting
182 it into the MDC under the key "txId".</p>
183
184
185 <pre class="prettyprint source">public class UserServletFilter implements Filter {
186
187 public void doFilter(ServletRequest request, ServletResponse response,
188 FilterChain chain) throws IOException, ServletException {
189
190 HttpServletRequest req = (HttpServletRequest) request;
191 HttpSession session = req.getSession();
192 MDC.put("txId", session.getId());
193 ...
194 try {
195 // invoke subsequent filters
196 chain.doFilter(request, response);
197 } finally {
198 // always clear the MDC at the end of the request
199 MDC.clear();
200 }
201 }
202 }</pre>
203
204
205 <p>By setting an appropriate discriminator in SMTPAppender, you can
206 can scatter incoming events into different buffers according to the
207 value returned by the discriminator. Given that each request session
208 is placed under the MDC key "txId", we can use an MDC-based
209 discriminator to isolate the logs generated by each transaction.
210 </p>
211
212 <pre class="prettyprint source">&lt;configuration scan="true" scanPeriod="3 seconds">
213
214 &lt;statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" />
215
216 &lt;appender name="SMTP" class="ch.qos.logback.classic.net.SMTPAppender">
217 &lt;smtpHost>NAME_OF_SMTP_HOST&lt;/smtpHost>
218 &lt;to>...&lt;/to>
219 &lt;from>...&lt;/from>
220
221 &lt;smtpHost>NAME_OF_SMTP_HOST&lt;/smtpHost>
222 &lt;to>[email protected]&lt;/to>
223 &lt;from>testing@...&lt;/from>
224 &lt;subject>Prime - %mdc{number} by %mdc{userid} &lt;/subject>
225 &lt;layout class="ch.qos.logback.classic.html.HTMLLayout">
226 &lt;pattern>%date%level%logger{24}%msg&lt;/pattern>
227 &lt;/layout>
228
229 &lt;evaluator class="ch.qos.logback.classic.boolex.JaninoEventEvaluator">
230 &lt;expression>
231 marker != null &amp;&amp; marker.contains("SMTP_TRIGGER")
232 &lt;/expression>
233 &lt;/evaluator>
234
235 <b>&lt;discriminator class="ch.qos.logback.classic.sift.MDCBasedDiscriminator"></b>
236 <b>&lt;key>txId&lt;/key></b>
237 <b>&lt;defaultValue>default&lt;/defaultValue></b>
238 <b>&lt;/discriminator></b>
239 &lt;/appender>
240
241 &lt;root level="DEBUG">
242 &lt;appender-ref ref="SMTP" />
243 &lt;/root>
244 &lt;/configuration> </pre>
245
246 <p>After starting the logback-demo web-application with the above
247 configuration file (with <span class="option">smtpHost</span> and
248 <span class="option">to</span> options adapted for my environment)
249 on localhost and then visiting the <a
250 href="http://localhost:8070/logback-demo/prime.jsp">Prime
251 number</a> page to factorize the number 123, I received the
252 following email:
253 </p>
254
255 <img src="images/factorEmail0.png" alt="selective email0"/>
256
257 <p>Note that the above email contains the logs generated by the
258 factorization of the number 123, without log pollution from any
259 other "transaction".
260 </p>
261
262 <h3>Selective triggering &amp; recipient addressing with transaction isolation</h3>
263
264 <p>In a real world scenario, receiving isolated transactions is not
265 enough. You would need to trigger outgoing emails only for certain
266 users, typically QA engineers such as Dave and Carol. Moreover, you
267 would want the emails generated by transaction made by Carol to
268 Carol's mailbox and those generated by Dave to Dave's mailbox.</p>
269
270 <p>Selective triggering and addressing are two distinct
271 problems. Depending on the exact circumstances, there are many ways
272 of tackling these two issues. However, for the sake of simplicity,
273 let us assume that the SMTP server at Fooware.com accepts <a
274 href="http://en.wikipedia.org/wiki/Email_address#Address_tags">address
275 tags</a>. Such an SMTP server treats an incoming message sent to
276 [email protected] as if it were addressed to
277 [email protected], effectively stripping the +xyz part.</p>
278
279 <p>Let us further assume that we can somehow extract the email
280 address of the user from the contents of her transaction, via a
281 database lookup or perhaps some other means. The extracted email
282 addressed is placed into the MDC under the key "txEmail".
283 </p>
284
285 <p>Upon a logging event marked as SMTP_TRIGGER, the following
286 configuration file will trigger an email message addressed to the
287 value of "%mdc{txEmail}" but only if it contains the string "+log".
288 </p>
289
290 <pre class="prettyprint source">&lt;configuration scan="true" scanPeriod="3 seconds">
291
292 &lt;statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" /&gt;
293
294 &lt;appender name="SMTP" class="ch.qos.logback.classic.net.SMTPAppender">
295 &lt;SMTPHost>NAME_OF_SMTP_HOST&lt;/SMTPHost>
296 <b>&lt;to>%mdc{txEmail}&lt;/to></b>
297 &lt;from>&lt;/from>
298 &lt;subject>Prime - %mdc{number}&lt;/subject>
299
300 &lt;layout class="ch.qos.logback.classic.html.HTMLLayout">
301 &lt;pattern>%date%level%logger{24}%msg&lt;/pattern>
302 &lt;/layout>
303
304 &lt;discriminator class="ch.qos.logback.classic.sift.MDCBasedDiscriminator">
305 &lt;key>txId&lt;/key>
306 &lt;defaultValue>default&lt;/defaultValue>
307 &lt;/discriminator>
308
309 &lt;evaluator class="ch.qos.logback.classic.boolex.JaninoEventEvaluator">
310 &lt;expression>
311 <b>(mdc != null &amp;amp;&amp;amp; mdc.get("txEmail") != null &amp;amp;&amp;amp; </b>
312 <b>((String) mdc.get("txEmail")).contains("+log") )</b>
313 &amp;amp;&amp;amp;
314 (marker != null &amp;&amp; marker.contains("SMTP_TRIGGER") )
315 &lt;/expression>
316 &lt;/evaluator>
317 &lt;/appender>
318
319 &lt;root level="DEBUG">
320 &lt;appender-ref ref="SMTP" />
321 &lt;/root>
322 &lt;/configuration> </pre>
323
324 <p>If your particular SMTP server does not handle address tags,
325 you can still use them within the evaluator but remove them in
326 the recipient address with the help of the <a
327 href="../manual/layouts.html#replace">%replace</a> conversion
328 word. Here is the relevant configuration snippet:</p>
329
330 <pre class="prettyprint source">&lt;appender name="SMTP" class="ch.qos.logback.classic.net.SMTPAppender">
331 &lt;to>%replace(%mdc{txEmail}){'\+log', ''}&lt;/to>
332 ...
333 &lt;/appender></pre>
334
335 <p>This replaces any occurrence of the string "+log" within the
336 string returned by %mdc{txEmail} with the empty string,
337 effectively erasing +log from the recipient address.</p>
338
339 <h3>Buffer management in very busy systems</h3>
340
341 <p>The solution described so far provides an amazingly flexible
342 solution to the initial problem. Indeed, any QA-engineer at
343 Fooware.com, say Carol, can have the logs generated by requests
344 she makes to Buscrit sent to her automatically by email. All she
345 has to do is to suffix the user part in her email address with
346 "+log" when she registers with Buscrit.
347 </p>
348
349 <p>By default <code>SMTPAppender</code> will cap the number of
350 buffers it maintains to the value of the <span
351 class="option">maxNumberOfBuffers</span> option (64 by default)
352 and automatically discards buffers untouched for at least 30
353 minutes. While this approach will work nicely in a test
354 environment with few transactions, in a very busy production
355 system, these buffer management mechanisms will cause Carol to
356 receive <a
357 href="../manual/appenders.html#bufferManagement">truncated log
358 buffers</a>. </p>
359
360 <p>To deal with this problem, we instruct SMTPAppender to discard
361 the appropriate buffer at the end of each transaction. This is done by
362 logging an event marked as "FINALIZE_SESSION". Here is a modified
363 version of <code>PrimeAction</code> which marks the end of a
364 transaction with "FINALIZE_SESSION".
365 </p>
366
367 <pre class="prettyprint source">package ch.qos.logback.demo.prime;
368
369 <b>import static ch.qos.logback.classic.ClassicConstants.FINALIZE_SESSION_MARKER;</b>
370
371 public class PrimeAction extends Action {
372
373 Logger logger = LoggerFactory.getLogger(PrimeAction.class);
374 static Marker SMTP_TRIGGER = MarkerFactory.getMarker("SMTP_TRIGGER");
375 static {
376 // markers can hold references to other markers
377 <b>SMTP_TRIGGER.add(FINALIZE_SESSION_MARKER);</b>
378 }
379
380 public ActionForward execute(ActionMapping actionMapping, ... ) throws Exception {
381
382 Long number = form.getNumber();
383 try {
384 ...
385 } finally {
386 <b>logger.info(SMTP_TRIGGER, "Prime computation ended");</b>
387 MDC.put("txId", null); // clear txId asap to avoid accidental rebirth
388 }
389 }
390 } </pre>
391
392
393 <p>Not that at the end of each transaction the appropriate buffer
394 is discarded, we can increase the value of <span
395 class="option">maxNumberOfBuffers</span> as shown in the next
396 configuration file..
397 </p>
398
399 <pre class="prettyprint source">&lt;configuration scan="true" scanPeriod="3 seconds">
400
401 &lt;statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" /&gt;
402
403 &lt;appender name="SMTP" class="ch.qos.logback.classic.net.SMTPAppender">
404 &lt;SMTPHost>NAME_OF_SMTP_HOST&lt;/SMTPHost>
405 &lt;to>%mdc{txEmail}&lt;/to>
406 &lt;from>&lt;/from>
407 &lt;subject>Prime - %mdc{number}&lt;/subject>
408
409 &lt;layout class="ch.qos.logback.classic.html.HTMLLayout">
410 &lt;pattern>%date%level%logger{24}%msg&lt;/pattern>
411 &lt;/layout>
412
413 &lt;discriminator class="ch.qos.logback.classic.sift.MDCBasedDiscriminator">
414 &lt;key>txId&lt;/key>
415 &lt;defaultValue>default&lt;/defaultValue>
416 &lt;/discriminator>
417
418 <b>&lt;cyclicBufferTracker class="ch.qos.logback.core.spi.CyclicBufferTracker"></b>
419 <b>&lt;maxNumberOfBuffers>512&lt;/maxNumberOfBuffers></b>
420 <b>&lt;/cyclicBufferTracker></b>
421
422 &lt;evaluator class="ch.qos.logback.classic.boolex.JaninoEventEvaluator">
423 &lt;expression>
424 (mdc != null &amp;amp;&amp;amp; mdc.get("txEmail") != null &amp;amp;&amp;amp;
425 ((String) mdc.get("txEmail")).contains("+log") )
426 &amp;amp;&amp;amp;
427 (marker != null &amp;&amp; marker.contains("SMTP_TRIGGER") )
428 &lt;/expression>
429 &lt;/evaluator>
430
431 &lt;root level="DEBUG">
432 &lt;appender-ref ref="SMTP" />
433 &lt;/root>
434 &lt;/configuration> </pre>
435
436 <p>With these latest changes, we can selectively send isolated
437 logs for selected transactions to the concerned recipient, even in
438 very busy production systems without excessive memory consumption.
439 </p>
440
441 <script src="../templates/footer.js" type="text/javascript"></script>
442 </div>
443 </body>
444 </html>
445