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     */
017    package org.apache.logging.log4j.core.appender;
018    
019    import java.io.Serializable;
020    import java.util.HashMap;
021    import java.util.Map;
022    
023    import org.apache.logging.log4j.core.Filter;
024    import org.apache.logging.log4j.core.Layout;
025    import org.apache.logging.log4j.core.config.Configuration;
026    import org.apache.logging.log4j.core.config.plugins.Plugin;
027    import org.apache.logging.log4j.core.config.plugins.PluginAliases;
028    import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
029    import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
030    import org.apache.logging.log4j.core.config.plugins.PluginElement;
031    import org.apache.logging.log4j.core.config.plugins.PluginFactory;
032    import org.apache.logging.log4j.core.layout.SerializedLayout;
033    import org.apache.logging.log4j.core.net.AbstractSocketManager;
034    import org.apache.logging.log4j.core.net.Advertiser;
035    import org.apache.logging.log4j.core.net.DatagramSocketManager;
036    import org.apache.logging.log4j.core.net.Protocol;
037    import org.apache.logging.log4j.core.net.SslSocketManager;
038    import org.apache.logging.log4j.core.net.TcpSocketManager;
039    import org.apache.logging.log4j.core.net.ssl.SslConfiguration;
040    import org.apache.logging.log4j.core.util.Booleans;
041    import org.apache.logging.log4j.util.EnglishEnums;
042    
043    /**
044     * An Appender that delivers events over socket connections. Supports both TCP and UDP.
045     */
046    @Plugin(name = "Socket", category = "Core", elementType = "appender", printObject = true)
047    public class SocketAppender extends AbstractOutputStreamAppender<AbstractSocketManager> {
048    
049        private static final long serialVersionUID = 1L;
050    
051        private Object advertisement;
052        private final Advertiser advertiser;
053    
054        protected SocketAppender(final String name, final Layout<? extends Serializable> layout, final Filter filter,
055                final AbstractSocketManager manager, final boolean ignoreExceptions, final boolean immediateFlush,
056                final Advertiser advertiser) {
057            super(name, layout, filter, ignoreExceptions, immediateFlush, manager);
058            if (advertiser != null) {
059                final Map<String, String> configuration = new HashMap<String, String>(layout.getContentFormat());
060                configuration.putAll(manager.getContentFormat());
061                configuration.put("contentType", layout.getContentType());
062                configuration.put("name", name);
063                this.advertisement = advertiser.advertise(configuration);
064            }
065            this.advertiser = advertiser;
066        }
067    
068        @Override
069        public void stop() {
070            super.stop();
071            if (this.advertiser != null) {
072                this.advertiser.unadvertise(this.advertisement);
073            }
074        }
075    
076        /**
077         * 
078         * @param host
079         *        The name of the host to connect to.
080         * @param portNum
081         *        The port to connect to on the target host.
082         * @param protocolStr
083         *        The Protocol to use.
084         * @param sslConfig
085         *        The SSL configuration file for TCP/SSL, ignored for UPD.
086         * @param delayMillis
087         *        The interval in which failed writes should be retried.
088         * @param immediateFail
089         *        True if the write should fail if no socket is immediately available.
090         * @param name
091         *        The name of the Appender.
092         * @param immediateFlush
093         *        "true" if data should be flushed on each write.
094         * @param ignore
095         *        If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise they are
096         *        propagated to the caller.
097         * @param layout
098         *        The layout to use (defaults to SerializedLayout).
099         * @param filter
100         *        The Filter or null.
101         * @param advertise
102         *        "true" if the appender configuration should be advertised, "false" otherwise.
103         * @param config
104         *        The Configuration
105         * @return A SocketAppender.
106         */
107        @PluginFactory
108        public static SocketAppender createAppender(
109                // @formatter:off
110                @PluginAttribute("host") final String host,
111                @PluginAttribute("port") final String portNum,
112                @PluginAttribute("protocol") final String protocolStr,
113                @PluginElement("SSL") final SslConfiguration sslConfig,
114                @PluginAliases("reconnectionDelay") // deprecated
115                @PluginAttribute("reconnectionDelayMillis") final String delayMillis,
116                @PluginAttribute("immediateFail") final String immediateFail,
117                @PluginAttribute("name") final String name,
118                @PluginAttribute("immediateFlush") final String immediateFlush,
119                @PluginAttribute("ignoreExceptions") final String ignore,
120                @PluginElement("Layout") Layout<? extends Serializable> layout,
121                @PluginElement("Filter") final Filter filter,
122                @PluginAttribute("advertise") final String advertise, 
123                @PluginConfiguration final Configuration config) {
124                // @formatter:on
125            boolean isFlush = Booleans.parseBoolean(immediateFlush, true);
126            final boolean isAdvertise = Boolean.parseBoolean(advertise);
127            final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
128            final boolean fail = Booleans.parseBoolean(immediateFail, true);
129            final int reconnectDelayMillis = AbstractAppender.parseInt(delayMillis, 0);
130            final int port = AbstractAppender.parseInt(portNum, 0);
131            if (layout == null) {
132                layout = SerializedLayout.createLayout();
133            }
134    
135            if (name == null) {
136                LOGGER.error("No name provided for SocketAppender");
137                return null;
138            }
139    
140            final Protocol protocol = EnglishEnums.valueOf(Protocol.class,
141                    protocolStr != null ? protocolStr : Protocol.TCP.name());
142            if (protocol == Protocol.UDP) {
143                isFlush = true;
144            }
145    
146            final AbstractSocketManager manager = createSocketManager(name, protocol, host, port, sslConfig,
147                    reconnectDelayMillis, fail, layout);
148    
149            return new SocketAppender(name, layout, filter, manager, ignoreExceptions, isFlush,
150                    isAdvertise ? config.getAdvertiser() : null);
151        }
152    
153        /**
154         * Creates an AbstractSocketManager for TCP, UDP, and SSL.
155         * 
156         * @throws IllegalArgumentException
157         *         if the protocol cannot be handled.
158         */
159        protected static AbstractSocketManager createSocketManager(final String name, Protocol protocol, final String host,
160                final int port, final SslConfiguration sslConfig, final int delayMillis, final boolean immediateFail,
161                final Layout<? extends Serializable> layout) {
162            if (protocol == Protocol.TCP && sslConfig != null) {
163                // Upgrade TCP to SSL if an SSL config is specified.
164                protocol = Protocol.SSL;
165            }
166            if (protocol != Protocol.SSL && sslConfig != null) {
167                LOGGER.info("Appender {} ignoring SSL configuration for {} protocol", name, protocol);
168            }
169            switch (protocol) {
170            case TCP:
171                return TcpSocketManager.getSocketManager(host, port, delayMillis, immediateFail, layout);
172            case UDP:
173                return DatagramSocketManager.getSocketManager(host, port, layout);
174            case SSL:
175                return SslSocketManager.getSocketManager(sslConfig, host, port, delayMillis, immediateFail, layout);
176            default:
177                throw new IllegalArgumentException(protocol.toString());
178            }
179        }
180    }