001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.classic.joran.action;
015
016import org.xml.sax.Attributes;
017
018import ch.qos.logback.classic.Logger;
019import ch.qos.logback.classic.LoggerContext;
020import ch.qos.logback.classic.net.SocketAppender;
021import ch.qos.logback.core.joran.action.Action;
022import ch.qos.logback.core.joran.spi.ActionException;
023import ch.qos.logback.core.joran.spi.InterpretationContext;
024
025public class ConsolePluginAction extends Action {
026
027    private static final String PORT_ATTR = "port";
028    private static final Integer DEFAULT_PORT = 4321;
029
030    @Override
031    public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException {
032        String portStr = attributes.getValue(PORT_ATTR);
033        Integer port = null;
034
035        if (portStr == null) {
036            port = DEFAULT_PORT;
037        } else {
038            try {
039                port = Integer.valueOf(portStr);
040            } catch (NumberFormatException ex) {
041                addError("Port " + portStr + " in ConsolePlugin config is not a correct number");
042            }
043        }
044
045        LoggerContext lc = (LoggerContext) ec.getContext();
046        SocketAppender appender = new SocketAppender();
047        appender.setContext(lc);
048        appender.setIncludeCallerData(true);
049        appender.setRemoteHost("localhost");
050        appender.setPort(port.intValue());
051        appender.start();
052        Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME);
053        root.addAppender(appender);
054
055        addInfo("Sending LoggingEvents to the plugin using port " + port);
056    }
057
058    @Override
059    public void end(InterpretationContext ec, String name) throws ActionException {
060
061    }
062}