1
2
3
4
5
6
7
8
9
10
11
12
13
14 package chapters.mdc;
15
16 import java.net.URL;
17
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20 import org.slf4j.MDC;
21
22 import ch.qos.logback.classic.LoggerContext;
23 import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
24 import ch.qos.logback.classic.joran.JoranConfigurator;
25 import ch.qos.logback.classic.spi.ILoggingEvent;
26 import ch.qos.logback.core.ConsoleAppender;
27 import ch.qos.logback.core.joran.spi.JoranException;
28 import ch.qos.logback.core.util.Loader;
29 import ch.qos.logback.core.util.StatusPrinter;
30
31 public class SimpleMDC {
32 static public void main(String[] args) throws Exception {
33
34
35 MDC.put("first", "Dorothy");
36
37
38
39 configureViaXML_File();
40
41
42
43
44
45
46 Logger logger = LoggerFactory.getLogger(SimpleMDC.class);
47
48 MDC.put("last", "Parker");
49
50
51
52 logger.info("Check enclosed.");
53 logger.debug("The most beautiful two words in English.");
54
55 MDC.put("first", "Richard");
56 MDC.put("last", "Nixon");
57 logger.info("I am not a crook.");
58 logger.info("Attributed to the former US president. 17 Nov 1973.");
59 }
60
61 static void programmaticConfiguration() {
62
63 LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
64 loggerContext.reset();
65 PatternLayoutEncoder layout = new PatternLayoutEncoder();
66 layout.setContext(loggerContext);
67 layout.setPattern("%X{first} %X{last} - %m%n");
68 layout.start();
69 ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
70 appender.setContext(loggerContext);
71 appender.setEncoder(layout);
72 appender.start();
73
74
75 ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("root");
76 root.addAppender(appender);
77 }
78
79 static void configureViaXML_File() {
80 LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
81 try {
82 JoranConfigurator configurator = new JoranConfigurator();
83 configurator.setContext(lc);
84 lc.reset();
85 URL url = Loader.getResourceBySelfClassLoader("chapters/mdc/simpleMDC.xml");
86 configurator.doConfigure(url);
87 } catch (JoranException je) {
88 StatusPrinter.print(lc);
89 }
90 }
91
92 }