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.spi.ILoggingEvent;
17 import ch.qos.logback.core.sift.Discriminator;
18 import ch.qos.logback.core.spi.ContextAwareBase;
19
20 /**
21 * This discriminator returns the value context to which this event is attached
22 * to. If the said value is null, then a default value is returned.
23 *
24 * <p>
25 * Both Key and the DefaultValue are user specified properties.
26 *
27 * @author Ceki Gülcü
28 *
29 */
30 public class ContextBasedDiscriminator extends ContextAwareBase implements
31 Discriminator<ILoggingEvent> {
32
33 private static final String KEY = "contextName";
34 private String defaultValue;
35 private boolean started = false;
36
37 public ContextBasedDiscriminator() {
38 }
39
40 /**
41 * Return the name of the current context name as found in the logging event.
42 */
43 public String getDiscriminatingValue(ILoggingEvent event) {
44 String contextName = event.getLoggerContextVO().getName();
45
46 if (contextName == null) {
47 return defaultValue;
48 } else {
49 return contextName;
50 }
51 }
52
53 public boolean isStarted() {
54 return started;
55 }
56
57 public void start() {
58 started = true;
59 }
60
61 public void stop() {
62 started = false;
63 }
64
65 public String getKey() {
66 return KEY;
67 }
68
69 public void setKey(String key) {
70 throw new UnsupportedOperationException(
71 "Key cannot be set. Using fixed key " + KEY);
72 }
73
74 /**
75 * @see #setDefaultValue(String)
76 * @return
77 */
78 public String getDefaultValue() {
79 return defaultValue;
80 }
81
82 /**
83 * The default context name in case the context name is not set for the
84 * current logging event.
85 *
86 * @param defaultValue
87 */
88 public void setDefaultValue(String defaultValue) {
89 this.defaultValue = defaultValue;
90 }
91 }