001package ch.qos.logback.classic.model.processor; 002 003import ch.qos.logback.classic.LoggerContext; 004import ch.qos.logback.classic.model.LoggerContextListenerModel; 005import ch.qos.logback.classic.spi.LoggerContextListener; 006import ch.qos.logback.core.Context; 007import ch.qos.logback.core.model.Model; 008import ch.qos.logback.core.model.processor.ModelHandlerBase; 009import ch.qos.logback.core.model.processor.ModelHandlerException; 010import ch.qos.logback.core.model.processor.ModelInterpretationContext; 011import ch.qos.logback.core.spi.ContextAware; 012import ch.qos.logback.core.spi.LifeCycle; 013import ch.qos.logback.core.util.OptionHelper; 014 015public class LoggerContextListenerModelHandler extends ModelHandlerBase { 016 boolean inError = false; 017 LoggerContextListener lcl; 018 019 public LoggerContextListenerModelHandler(Context context) { 020 super(context); 021 } 022 023 static public ModelHandlerBase makeInstance(Context context, ModelInterpretationContext ic) { 024 return new LoggerContextListenerModelHandler(context); 025 } 026 027 @Override 028 protected Class<LoggerContextListenerModel> getSupportedModelClass() { 029 return LoggerContextListenerModel.class; 030 } 031 032 @Override 033 public void handle(ModelInterpretationContext mic, Model model) throws ModelHandlerException { 034 LoggerContextListenerModel lclModel = (LoggerContextListenerModel) model; 035 036 String className = lclModel.getClassName(); 037 if (OptionHelper.isNullOrEmpty(className)) { 038 addError("Empty class name for LoggerContextListener"); 039 inError = true; 040 } else { 041 className = mic.getImport(className); 042 } 043 044 try { 045 lcl = (LoggerContextListener) OptionHelper.instantiateByClassName(className, LoggerContextListener.class, 046 context); 047 048 if (lcl instanceof ContextAware) { 049 ((ContextAware) lcl).setContext(context); 050 } 051 052 mic.pushObject(lcl); 053 addInfo("Adding LoggerContextListener of type [" + className + "] to the object stack"); 054 055 } catch (Exception oops) { 056 inError = true; 057 addError("Could not create LoggerContextListener of type " + className + "].", oops); 058 } 059 } 060 061 @Override 062 public void postHandle(ModelInterpretationContext mic, Model model) throws ModelHandlerException { 063 if (inError) { 064 return; 065 } 066 Object o = mic.peekObject(); 067 068 if (o != lcl) { 069 addWarn("The object on the top the of the stack is not the LoggerContextListener pushed earlier."); 070 } else { 071 if (lcl instanceof LifeCycle) { 072 ((LifeCycle) lcl).start(); 073 addInfo("Starting LoggerContextListener"); 074 } 075 ((LoggerContext) context).addListener(lcl); 076 mic.popObject(); 077 } 078 } 079}