1
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) throws ActionException {
33
34 inError = false;
35
36 String className = attributes.getValue(CLASS_ATTRIBUTE);
37 if (OptionHelper.isEmpty(className)) {
38 addError("Mandatory \"" + CLASS_ATTRIBUTE + "\" attribute not set for <loggerContextListener> element");
39 inError = true;
40 return;
41 }
42
43 try {
44 lcl = (LoggerContextListener) OptionHelper.instantiateByClassName(className, LoggerContextListener.class, context);
45
46 if (lcl instanceof ContextAware) {
47 ((ContextAware) lcl).setContext(context);
48 }
49
50 ec.pushObject(lcl);
51 addInfo("Adding LoggerContextListener of type [" + className + "] to the object stack");
52
53 } catch (Exception oops) {
54 inError = true;
55 addError("Could not create LoggerContextListener of type " + className + "].", oops);
56 }
57 }
58
59 @Override
60 public void end(InterpretationContext ec, String name) throws ActionException {
61 if (inError) {
62 return;
63 }
64 Object o = ec.peekObject();
65
66 if (o != lcl) {
67 addWarn("The object on the top the of the stack is not the LoggerContextListener pushed earlier.");
68 } else {
69 if (lcl instanceof LifeCycle) {
70 ((LifeCycle) lcl).start();
71 addInfo("Starting LoggerContextListener");
72 }
73 ((LoggerContext) context).addListener(lcl);
74 ec.popObject();
75 }
76 }
77
78 }
79