View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, 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 org.xml.sax.Attributes;
17  
18  import ch.qos.logback.classic.Logger;
19  import ch.qos.logback.classic.LoggerContext;
20  import ch.qos.logback.classic.net.SocketAppender;
21  import ch.qos.logback.core.joran.action.Action;
22  import ch.qos.logback.core.joran.spi.ActionException;
23  import ch.qos.logback.core.joran.spi.SaxEventInterpretationContext;
24  
25  public class ConsolePluginAction extends Action {
26  
27      private static final String PORT_ATTR = "port";
28      private static final Integer DEFAULT_PORT = 4321;
29  
30      @Override
31      public void begin(SaxEventInterpretationContext ec, String name, Attributes attributes) throws ActionException {
32          String portStr = attributes.getValue(PORT_ATTR);
33          Integer port = null;
34  
35          if (portStr == null) {
36              port = DEFAULT_PORT;
37          } else {
38              try {
39                  port = Integer.valueOf(portStr);
40              } catch (NumberFormatException ex) {
41                  addError("Port " + portStr + " in ConsolePlugin config is not a correct number");
42                  addError("Abandoning configuration of ConsolePlugin.");
43                  return;
44              }
45          }
46  
47          LoggerContext lc = (LoggerContext) ec.getContext();
48          SocketAppender appender = new SocketAppender();
49          appender.setContext(lc);
50          appender.setIncludeCallerData(true);
51          appender.setRemoteHost("localhost");
52          appender.setPort(port.intValue());
53          appender.start();
54          Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME);
55          root.addAppender(appender);
56  
57          addInfo("Sending LoggingEvents to the plugin using port " + port);
58      }
59  
60      @Override
61      public void end(SaxEventInterpretationContext ec, String name) throws ActionException {
62  
63      }
64  }