View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, 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.Discriminator;
21  import ch.qos.logback.core.spi.ContextAwareBase;
22  
23  /**
24   * This discriminator returns the value context as determined by JNDI. If the
25   * said value is null, then a default value is returned.
26   * 
27   * <p>
28   * Both Key and the DefaultValue are user specified properties.
29   * 
30   * @author Ceki G&uuml;lc&uuml;
31   * 
32   */
33  public class JNDIBasedContextDiscriminator extends ContextAwareBase implements
34      Discriminator<ILoggingEvent> {
35  
36    private static final String KEY = "contextName";
37    private String defaultValue;
38    private boolean started = false;
39  
40    public JNDIBasedContextDiscriminator() {
41    }
42  
43    /**
44     * Return the name of the current context name as found in the logging event.
45     */
46    public String getDiscriminatingValue(ILoggingEvent event) {
47      ContextSelector selector = ContextSelectorStaticBinder.getSingleton()
48          .getContextSelector();
49  
50      if (selector == null) {
51        return defaultValue;
52      }
53  
54      LoggerContext lc = selector.getLoggerContext();
55      if (lc == null) {
56        return defaultValue;
57      }
58  
59      return lc.getName();
60    }
61  
62    public boolean isStarted() {
63      return started;
64    }
65  
66    public void start() {
67      started = true;
68    }
69  
70    public void stop() {
71      started = false;
72    }
73  
74    public String getKey() {
75      return KEY;
76    }
77  
78    public void setKey(String key) {
79      throw new UnsupportedOperationException(
80          "Key cannot be set. Using fixed key " + KEY);
81    }
82  
83    /**
84     * @see #setDefaultValue(String)
85     * @return
86     */
87    public String getDefaultValue() {
88      return defaultValue;
89    }
90  
91    /**
92     * The default context name in case the context name is not set for the
93     * current logging event.
94     * 
95     * @param defaultValue
96     */
97    public void setDefaultValue(String defaultValue) {
98      this.defaultValue = defaultValue;
99    }
100 }