View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
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  }