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.spi.ILoggingEvent;
017import ch.qos.logback.core.sift.AbstractDiscriminator;
018
019/**
020 * This discriminator returns the value context to which this event is attached
021 * to. If the said value is null, then a default value is returned.
022 * 
023 * <p>
024 * Both Key and the DefaultValue are user specified properties.
025 * 
026 * @author Ceki G&uuml;lc&uuml;
027 * 
028 */
029public class ContextBasedDiscriminator extends AbstractDiscriminator<ILoggingEvent> {
030
031    private static final String KEY = "contextName";
032    private String defaultValue;
033
034    /**
035     * Return the name of the current context name as found in the logging event.
036     */
037    public String getDiscriminatingValue(ILoggingEvent event) {
038        String contextName = event.getLoggerContextVO().getName();
039
040        if (contextName == null) {
041            return defaultValue;
042        } else {
043            return contextName;
044        }
045    }
046
047    public String getKey() {
048        return KEY;
049    }
050
051    public void setKey(String key) {
052        throw new UnsupportedOperationException("Key cannot be set. Using fixed key " + KEY);
053    }
054
055    /**
056     * @see #setDefaultValue(String)
057     * @return
058     */
059    public String getDefaultValue() {
060        return defaultValue;
061    }
062
063    /**
064     * The default context name in case the context name is not set for the
065     * current logging event.
066     * 
067     * @param defaultValue
068     */
069    public void setDefaultValue(String defaultValue) {
070        this.defaultValue = defaultValue;
071    }
072}