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