View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.classic.sift;
15  
16  import ch.qos.logback.classic.LoggerContext;
17  import ch.qos.logback.classic.selector.ContextSelector;
18  import ch.qos.logback.classic.spi.ILoggingEvent;
19  import ch.qos.logback.classic.util.ContextSelectorStaticBinder;
20  import ch.qos.logback.core.sift.AbstractDiscriminator;
21  
22  /**
23   * This discriminator returns the value context as determined by JNDI. If the
24   * said value is null, then a default value is returned.
25   * 
26   * <p>
27   * Both Key and the DefaultValue are user specified properties.
28   * 
29   * @author Ceki G&uuml;lc&uuml;
30   * 
31   */
32  public class JNDIBasedContextDiscriminator extends AbstractDiscriminator<ILoggingEvent> {
33  
34      private static final String KEY = "contextName";
35      private String defaultValue;
36  
37      /**
38       * Return the name of the current context name as found in the logging event.
39       */
40      public String getDiscriminatingValue(ILoggingEvent event) {
41          ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
42  
43          if (selector == null) {
44              return defaultValue;
45          }
46  
47          LoggerContext lc = selector.getLoggerContext();
48          if (lc == null) {
49              return defaultValue;
50          }
51  
52          return lc.getName();
53      }
54  
55      public String getKey() {
56          return KEY;
57      }
58  
59      public void setKey(String key) {
60          throw new UnsupportedOperationException("Key cannot be set. Using fixed key " + KEY);
61      }
62  
63      /**
64       * @see #setDefaultValue(String)
65       * @return
66       */
67      public String getDefaultValue() {
68          return defaultValue;
69      }
70  
71      /**
72       * The default context name in case the context name is not set for the
73       * current logging event.
74       * 
75       * @param defaultValue
76       */
77      public void setDefaultValue(String defaultValue) {
78          this.defaultValue = defaultValue;
79      }
80  }