1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package ch.qos.logback.classic.model.processor;
16
17 import ch.qos.logback.classic.LoggerContext;
18 import ch.qos.logback.classic.model.LoggerContextListenerModel;
19 import ch.qos.logback.classic.spi.LoggerContextListener;
20 import ch.qos.logback.core.Context;
21 import ch.qos.logback.core.model.Model;
22 import ch.qos.logback.core.model.processor.ModelHandlerBase;
23 import ch.qos.logback.core.model.processor.ModelHandlerException;
24 import ch.qos.logback.core.model.processor.ModelInterpretationContext;
25 import ch.qos.logback.core.spi.ContextAware;
26 import ch.qos.logback.core.spi.LifeCycle;
27 import ch.qos.logback.core.util.OptionHelper;
28
29 public class LoggerContextListenerModelHandler extends ModelHandlerBase {
30 boolean inError = false;
31 LoggerContextListener lcl;
32
33 public LoggerContextListenerModelHandler(Context context) {
34 super(context);
35 }
36
37 static public ModelHandlerBase makeInstance(Context context, ModelInterpretationContext ic) {
38 return new LoggerContextListenerModelHandler(context);
39 }
40
41 @Override
42 protected Class<LoggerContextListenerModel> getSupportedModelClass() {
43 return LoggerContextListenerModel.class;
44 }
45
46 @Override
47 public void handle(ModelInterpretationContext mic, Model model) throws ModelHandlerException {
48 LoggerContextListenerModel lclModel = (LoggerContextListenerModel) model;
49
50 String className = lclModel.getClassName();
51 if (OptionHelper.isNullOrEmptyOrAllSpaces(className)) {
52 addError("Empty class name for LoggerContextListener");
53 inError = true;
54 } else {
55 className = mic.getImport(className);
56 }
57
58 try {
59 lcl = (LoggerContextListener) OptionHelper.instantiateByClassName(className, LoggerContextListener.class,
60 context);
61
62 if (lcl instanceof ContextAware) {
63 ((ContextAware) lcl).setContext(context);
64 }
65
66 mic.pushObject(lcl);
67 addInfo("Adding LoggerContextListener of type [" + className + "] to the object stack");
68
69 } catch (Exception oops) {
70 inError = true;
71 addError("Could not create LoggerContextListener of type " + className + "].", oops);
72 }
73 }
74
75 @Override
76 public void postHandle(ModelInterpretationContext mic, Model model) throws ModelHandlerException {
77 if (inError) {
78 return;
79 }
80 Object o = mic.peekObject();
81
82 if (o != lcl) {
83 addWarn("The object on the top the of the stack is not the LoggerContextListener pushed earlier.");
84 } else {
85 if (lcl instanceof LifeCycle) {
86 ((LifeCycle) lcl).start();
87 addInfo("Starting LoggerContextListener");
88 }
89 ((LoggerContext) context).addListener(lcl);
90 mic.popObject();
91 }
92 }
93 }