1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.classic.joran.action;
15
16 import ch.qos.logback.classic.spi.LoggerContextListener;
17 import ch.qos.logback.core.spi.ContextAware;
18 import ch.qos.logback.core.spi.LifeCycle;
19 import org.xml.sax.Attributes;
20
21 import ch.qos.logback.classic.LoggerContext;
22 import ch.qos.logback.core.joran.action.Action;
23 import ch.qos.logback.core.joran.spi.ActionException;
24 import ch.qos.logback.core.joran.spi.InterpretationContext;
25 import ch.qos.logback.core.util.OptionHelper;
26
27 public class LoggerContextListenerAction extends Action {
28 boolean inError = false;
29 LoggerContextListener lcl;
30
31 @Override
32 public void begin(InterpretationContext ec, String name, Attributes attributes)
33 throws ActionException {
34
35 inError = false;
36
37 String className = attributes.getValue(CLASS_ATTRIBUTE);
38 if (OptionHelper.isEmpty(className)) {
39 addError("Mandatory \"" + CLASS_ATTRIBUTE
40 + "\" attribute not set for <loggerContextListener> element");
41 inError = true;
42 return;
43 }
44
45 try {
46 lcl = (LoggerContextListener) OptionHelper.instantiateByClassName(
47 className, LoggerContextListener.class, context);
48
49 if(lcl instanceof ContextAware) {
50 ((ContextAware) lcl).setContext(context);
51 }
52
53 ec.pushObject(lcl);
54 addInfo("Adding LoggerContextListener of type [" + className
55 + "] to the object stack");
56
57 } catch (Exception oops) {
58 inError = true;
59 addError("Could not create LoggerContextListener of type " + className + "].", oops);
60 }
61 }
62
63 @Override
64 public void end(InterpretationContext ec, String name) throws ActionException {
65 if (inError) {
66 return;
67 }
68 Object o = ec.peekObject();
69
70 if (o != lcl) {
71 addWarn("The object on the top the of the stack is not the LoggerContextListener pushed earlier.");
72 } else {
73 if (lcl instanceof LifeCycle) {
74 ((LifeCycle) lcl).start();
75 addInfo("Starting LoggerContextListener");
76 }
77 ((LoggerContext) context).addListener(lcl);
78 ec.popObject();
79 }
80 }
81
82 }