View Javadoc

1   /*
2    * Grapht, an open source dependency injector.
3    * Copyright 2014-2015 various contributors (see CONTRIBUTORS.txt)
4    * Copyright 2010-2014 Regents of the University of Minnesota
5    *
6    * This program is free software; you can redistribute it and/or modify
7    * it under the terms of the GNU Lesser General Public License as
8    * published by the Free Software Foundation; either version 2.1 of the
9    * License, or (at your option) any later version.
10   *
11   * This program is distributed in the hope that it will be useful, but WITHOUT
12   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13   * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14   * details.
15   *
16   * You should have received a copy of the GNU General Public License along with
17   * this program; if not, write to the Free Software Foundation, Inc., 51
18   * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19   */
20  package org.grouplens.grapht.util;
21  
22  import java.util.Collections;
23  import java.util.Map;
24  import org.slf4j.MDC;
25  
26  /**
27   * Utility class to manage log data with {@link MDC}.  This class allows MDC parameters
28   * to be set, and popped back off when the context is finished.
29   */
30  
31  public class LogContext {
32      @SuppressWarnings("rawtypes")
33  
34      private final Map memory = MDC.getCopyOfContextMap();
35  
36      private  LogContext() {}
37  
38      /**
39       * Method creates a new log context,
40       * capturing the MDC's current data to be
41       * restored when finish() is called.
42       */
43      static public  LogContext create() {
44          return new LogContext();
45      }
46  
47      /**
48       * Set a key in the MDC environment.
49       * @param key The key to set.
50       * @param value The key's value.
51       * @see MDC#put(String, String)
52       */
53      public void put(String key, String value) {
54          MDC.put(key, value);
55      }
56  
57      /**
58       * Finish the context.  This restores the MDC context map to the value it had when the
59       * log context was created.
60       */
61      public void finish() {
62          MDC.setContextMap(memory == null ? Collections.EMPTY_MAP : memory);
63      }
64  }
65