001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.core.appender;
018
019import java.io.Serializable;
020import java.util.HashMap;
021import java.util.Map;
022
023import org.apache.logging.log4j.core.Filter;
024import org.apache.logging.log4j.core.Layout;
025import org.apache.logging.log4j.core.config.Configuration;
026import org.apache.logging.log4j.core.config.plugins.Plugin;
027import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
028import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
029import org.apache.logging.log4j.core.config.plugins.PluginElement;
030import org.apache.logging.log4j.core.config.plugins.PluginFactory;
031import org.apache.logging.log4j.core.layout.SerializedLayout;
032import org.apache.logging.log4j.core.net.AbstractSocketManager;
033import org.apache.logging.log4j.core.net.Advertiser;
034import org.apache.logging.log4j.core.net.DatagramSocketManager;
035import org.apache.logging.log4j.core.net.Protocol;
036import org.apache.logging.log4j.core.net.SslSocketManager;
037import org.apache.logging.log4j.core.net.TcpSocketManager;
038import org.apache.logging.log4j.core.net.ssl.SslConfiguration;
039import org.apache.logging.log4j.core.util.Booleans;
040import org.apache.logging.log4j.util.EnglishEnums;
041
042/**
043 * An Appender that delivers events over socket connections. Supports both TCP and UDP.
044 */
045@Plugin(name = "Socket", category = "Core", elementType = "appender", printObject = true)
046public class SocketAppender extends AbstractOutputStreamAppender<AbstractSocketManager> {
047    private Object advertisement;
048    private final Advertiser advertiser;
049
050    protected SocketAppender(final String name, final Layout<? extends Serializable> layout, final Filter filter,
051            final AbstractSocketManager manager, final boolean ignoreExceptions, final boolean immediateFlush,
052            final Advertiser advertiser) {
053        super(name, layout, filter, ignoreExceptions, immediateFlush, manager);
054        if (advertiser != null) {
055            final Map<String, String> configuration = new HashMap<String, String>(layout.getContentFormat());
056            configuration.putAll(manager.getContentFormat());
057            configuration.put("contentType", layout.getContentType());
058            configuration.put("name", name);
059            this.advertisement = advertiser.advertise(configuration);
060        }
061        this.advertiser = advertiser;
062    }
063
064    @Override
065    public void stop() {
066        super.stop();
067        if (this.advertiser != null) {
068            this.advertiser.unadvertise(this.advertisement);
069        }
070    }
071
072    /**
073     * 
074     * @param host
075     *        The name of the host to connect to.
076     * @param portNum
077     *        The port to connect to on the target host.
078     * @param protocolStr
079     *        The Protocol to use.
080     * @param sslConfig
081     *        The SSL configuration file for TCP/SSL, ignored for UPD.
082     * @param delay
083     *        The interval in which failed writes should be retried.
084     * @param immediateFail
085     *        True if the write should fail if no socket is immediately available.
086     * @param name
087     *        The name of the Appender.
088     * @param immediateFlush
089     *        "true" if data should be flushed on each write.
090     * @param ignore
091     *        If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise they are
092     *        propagated to the caller.
093     * @param layout
094     *        The layout to use (defaults to SerializedLayout).
095     * @param filter
096     *        The Filter or null.
097     * @param advertise
098     *        "true" if the appender configuration should be advertised, "false" otherwise.
099     * @param config
100     *        The Configuration
101     * @return A SocketAppender.
102     */
103    @PluginFactory
104    public static SocketAppender createAppender(
105            // @formatter:off
106            @PluginAttribute("host") final String host,
107            @PluginAttribute("port") final String portNum,
108            @PluginAttribute("protocol") final String protocolStr,
109            @PluginElement("SSL") final SslConfiguration sslConfig,
110            @PluginAttribute("reconnectionDelay") final String delay,
111            @PluginAttribute("immediateFail") final String immediateFail,
112            @PluginAttribute("name") final String name,
113            @PluginAttribute("immediateFlush") final String immediateFlush,
114            @PluginAttribute("ignoreExceptions") final String ignore,
115            @PluginElement("Layout") Layout<? extends Serializable> layout,
116            @PluginElement("Filter") final Filter filter,
117            @PluginAttribute("advertise") final String advertise, 
118            @PluginConfiguration final Configuration config) {
119            // @formatter:on
120        boolean isFlush = Booleans.parseBoolean(immediateFlush, true);
121        final boolean isAdvertise = Boolean.parseBoolean(advertise);
122        final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
123        final boolean fail = Booleans.parseBoolean(immediateFail, true);
124        final int reconnectDelay = AbstractAppender.parseInt(delay, 0);
125        final int port = AbstractAppender.parseInt(portNum, 0);
126        if (layout == null) {
127            layout = SerializedLayout.createLayout();
128        }
129
130        if (name == null) {
131            LOGGER.error("No name provided for SocketAppender");
132            return null;
133        }
134
135        final Protocol protocol = EnglishEnums.valueOf(Protocol.class,
136                protocolStr != null ? protocolStr : Protocol.TCP.name());
137        if (protocol == Protocol.UDP) {
138            isFlush = true;
139        }
140
141        final AbstractSocketManager manager = createSocketManager(name, protocol, host, port, sslConfig,
142                reconnectDelay, fail, layout);
143
144        return new SocketAppender(name, layout, filter, manager, ignoreExceptions, isFlush,
145                isAdvertise ? config.getAdvertiser() : null);
146    }
147
148    /**
149     * Creates an AbstractSocketManager for TCP, UDP, and SSL.
150     * 
151     * @throws IllegalArgumentException
152     *         if the protocol cannot be handled.
153     */
154    protected static AbstractSocketManager createSocketManager(final String name, Protocol protocol, final String host,
155            final int port, final SslConfiguration sslConfig, final int delay, final boolean immediateFail,
156            final Layout<? extends Serializable> layout) {
157        if (protocol == Protocol.TCP && sslConfig != null) {
158            // Upgrade TCP to SSL if an SSL config is specified.
159            protocol = Protocol.SSL;
160        }
161        if (protocol != Protocol.SSL && sslConfig != null) {
162            LOGGER.info("Appender {} ignoring SSL configuration for {} protocol", name, protocol);
163        }
164        switch (protocol) {
165        case TCP:
166            return TcpSocketManager.getSocketManager(host, port, delay, immediateFail, layout);
167        case UDP:
168            return DatagramSocketManager.getSocketManager(host, port, layout);
169        case SSL:
170            return SslSocketManager.getSocketManager(sslConfig, host, port, delay, immediateFail, layout);
171        default:
172            throw new IllegalArgumentException(protocol.toString());
173        }
174    }
175}