001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.classic.sift;
015
016import ch.qos.logback.classic.LoggerContext;
017import ch.qos.logback.classic.selector.ContextSelector;
018import ch.qos.logback.classic.spi.ILoggingEvent;
019import ch.qos.logback.classic.util.ContextSelectorStaticBinder;
020import ch.qos.logback.core.sift.AbstractDiscriminator;
021
022/**
023 * This discriminator returns the value context as determined by JNDI. If the
024 * said value is null, then a default value is returned.
025 * 
026 * <p>
027 * Both Key and the DefaultValue are user specified properties.
028 * 
029 * @author Ceki G&uuml;lc&uuml;
030 * 
031 */
032public class JNDIBasedContextDiscriminator extends AbstractDiscriminator<ILoggingEvent> {
033
034    private static final String KEY = "contextName";
035    private String defaultValue;
036
037    /**
038     * Return the name of the current context name as found in the logging event.
039     */
040    public String getDiscriminatingValue(ILoggingEvent event) {
041        ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
042
043        if (selector == null) {
044            return defaultValue;
045        }
046
047        LoggerContext lc = selector.getLoggerContext();
048        if (lc == null) {
049            return defaultValue;
050        }
051
052        return lc.getName();
053    }
054
055    public String getKey() {
056        return KEY;
057    }
058
059    public void setKey(String key) {
060        throw new UnsupportedOperationException("Key cannot be set. Using fixed key " + KEY);
061    }
062
063    /**
064     * @see #setDefaultValue(String)
065     * @return
066     */
067    public String getDefaultValue() {
068        return defaultValue;
069    }
070
071    /**
072     * The default context name in case the context name is not set for the current
073     * logging event.
074     * 
075     * @param defaultValue
076     */
077    public void setDefaultValue(String defaultValue) {
078        this.defaultValue = defaultValue;
079    }
080}