View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * 
4    * Copyright (C) 1999-2006, QOS.ch
5    * 
6    * This library is free software, you can redistribute it and/or modify it under
7    * the terms of the GNU Lesser General Public License as published by the Free
8    * Software Foundation.
9    */
10  
11  package chapter7;
12  
13  import org.slf4j.LoggerFactory;
14  import org.slf4j.MDC;
15  
16  import ch.qos.logback.classic.Logger;
17  import ch.qos.logback.classic.PatternLayout;
18  import ch.qos.logback.classic.spi.LoggingEvent;
19  import ch.qos.logback.core.ConsoleAppender;
20  
21  public class SimpleMDC {
22    static public void main(String[] args) throws Exception {
23      // You can put values in the MDC at any time. We first put the
24      // first name
25      MDC.put("first", "Dorothy");
26  
27      // Configure logback
28      PatternLayout layout = new PatternLayout();
29      layout.setPattern("%X{first} %X{last} - %m%n");
30      layout.start();
31      ConsoleAppender<LoggingEvent> appender = new ConsoleAppender<LoggingEvent>();
32      appender.setLayout(layout);
33      appender.start();
34      Logger root = (Logger)LoggerFactory.getLogger("root");
35      root.addAppender(appender);
36      
37      // get a logger
38      Logger logger = (Logger)LoggerFactory.getLogger(SimpleMDC.class);
39  
40      // We now put the last name
41      MDC.put("last", "Parker");
42  
43      // The most beautiful two words in the English language according
44      // to Dorothy Parker:
45      logger.info("Check enclosed.");
46      logger.debug("The most beautiful two words in English.");
47  
48      MDC.put("first", "Richard");
49      MDC.put("last", "Nixon");
50      logger.info("I am not a crook.");
51      logger.info("Attributed to the former US president. 17 Nov 1973.");
52    }
53  }