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 org.apache.logging.log4j.LoggingException;
020    import org.apache.logging.log4j.core.Appender;
021    import org.apache.logging.log4j.core.Filter;
022    import org.apache.logging.log4j.core.LogEvent;
023    import org.apache.logging.log4j.core.config.AppenderControl;
024    import org.apache.logging.log4j.core.config.Configuration;
025    import org.apache.logging.log4j.core.config.plugins.Plugin;
026    import org.apache.logging.log4j.core.config.plugins.PluginAttr;
027    import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
028    import org.apache.logging.log4j.core.config.plugins.PluginElement;
029    import org.apache.logging.log4j.core.config.plugins.PluginFactory;
030    import org.apache.logging.log4j.core.helpers.Constants;
031    
032    import java.util.ArrayList;
033    import java.util.List;
034    import java.util.Map;
035    
036    /**
037     * The FailoverAppender will capture exceptions in an Appender and then route the event
038     * to a different appender. Hopefully it is obvious that the Appenders must be configured
039     * to not suppress exceptions for the FailoverAppender to work.
040     */
041    @Plugin(name = "Failover", type = "Core", elementType = "appender", printObject = true)
042    public final class FailoverAppender extends AbstractAppender {
043    
044        private static final int DEFAULT_INTERVAL = 60 * Constants.MILLIS_IN_SECONDS;
045    
046        private final String primaryRef;
047    
048        private final String[] failovers;
049    
050        private final Configuration config;
051    
052        private AppenderControl primary;
053    
054        private final List<AppenderControl> failoverAppenders = new ArrayList<AppenderControl>();
055    
056        private final long interval;
057    
058        private long nextCheck = 0;
059    
060        private volatile boolean failure = false;
061    
062        private FailoverAppender(final String name, final Filter filter, final String primary, final String[] failovers,
063                                 final int interval, final Configuration config, final boolean handleExceptions) {
064            super(name, filter, null, handleExceptions);
065            this.primaryRef = primary;
066            this.failovers = failovers;
067            this.config = config;
068            this.interval = interval;
069        }
070    
071    
072        @Override
073        public void start() {
074            final Map<String, Appender<?>> map = config.getAppenders();
075            int errors = 0;
076            if (map.containsKey(primaryRef)) {
077                primary = new AppenderControl(map.get(primaryRef), null, null);
078            } else {
079                LOGGER.error("Unable to locate primary Appender " + primaryRef);
080                ++errors;
081            }
082            for (final String name : failovers) {
083                if (map.containsKey(name)) {
084                    failoverAppenders.add(new AppenderControl(map.get(name), null, null));
085                } else {
086                    LOGGER.error("Failover appender " + name + " is not configured");
087                }
088            }
089            if (failoverAppenders.size() == 0) {
090                LOGGER.error("No failover appenders are available");
091                ++errors;
092            }
093            if (errors == 0) {
094                super.start();
095            }
096        }
097    
098        /**
099         * Handle the Log event.
100         * @param event The LogEvent.
101         */
102        public void append(final LogEvent event) {
103            final RuntimeException re = null;
104            if (!isStarted()) {
105                error("FailoverAppender " + getName() + " did not start successfully");
106                return;
107            }
108            if (!failure) {
109                callAppender(event);
110            } else {
111                final long current = System.currentTimeMillis();
112                if (current >= nextCheck) {
113                    callAppender(event);
114                } else {
115                    failover(event, null);
116                }
117            }
118        }
119    
120        private void callAppender(final LogEvent event) {
121            try {
122                primary.callAppender(event);
123            } catch (final Exception ex) {
124                nextCheck = System.currentTimeMillis() + interval;
125                failure = true;
126                failover(event, ex);
127            }
128        }
129    
130        private void failover(final LogEvent event, final Exception ex) {
131            final RuntimeException re = ex != null ? new LoggingException(ex) : null;
132            boolean written = false;
133            Exception failoverException = null;
134            for (final AppenderControl control : failoverAppenders) {
135                try {
136                    control.callAppender(event);
137                    written = true;
138                    break;
139                } catch (final Exception fex) {
140                    if (failoverException == null) {
141                        failoverException = fex;
142                    }
143                }
144            }
145            if (!written && !isExceptionSuppressed()) {
146                if (re != null) {
147                    throw re;
148                } else {
149                    throw new LoggingException("Unable to write to failover appenders", failoverException);
150                }
151            }
152        }
153    
154        @Override
155        public String toString() {
156            final StringBuilder sb = new StringBuilder(getName());
157            sb.append(" primary=").append(primary).append(", failover={");
158            boolean first = true;
159            for (final String str : failovers) {
160                if (!first) {
161                    sb.append(", ");
162                }
163                sb.append(str);
164                first = false;
165            }
166            sb.append("}");
167            return sb.toString();
168        }
169    
170        /**
171         * Create a Failover Appender.
172         * @param name The name of the Appender (required).
173         * @param primary The name of the primary Appender (required).
174         * @param failovers The name of one or more Appenders to fail over to (at least one is required).
175         * @param interval The retry interval.
176         * @param config The current Configuration (passed by the Configuration when the appender is created).
177         * @param filter A Filter (optional).
178         * @param suppress "true" if exceptions should be hidden from the application, "false" otherwise.
179         * The default is "true".
180         * @return The FailoverAppender that was created.
181         */
182        @PluginFactory
183        public static FailoverAppender createAppender(@PluginAttr("name") final String name,
184                                                      @PluginAttr("primary") final String primary,
185                                                      @PluginElement("failovers") final String[] failovers,
186                                                      @PluginAttr("retryInterval") final String interval,
187                                                      @PluginConfiguration final Configuration config,
188                                                      @PluginElement("filters") final Filter filter,
189                                                      @PluginAttr("suppressExceptions") final String suppress) {
190            if (name == null) {
191                LOGGER.error("A name for the Appender must be specified");
192                return null;
193            }
194            if (primary == null) {
195                LOGGER.error("A primary Appender must be specified");
196                return null;
197            }
198            if (failovers == null || failovers.length == 0) {
199                LOGGER.error("At least one failover Appender must be specified");
200                return null;
201            }
202    
203            int retryInterval;
204            if (interval == null) {
205                retryInterval = DEFAULT_INTERVAL;
206            } else {
207                try {
208                    final int value = Integer.parseInt(interval);
209                    if (value >= 0) {
210                        retryInterval = value * Constants.MILLIS_IN_SECONDS;
211                    } else {
212                        LOGGER.warn("Interval " + interval + " is less than zero. Using default");
213                        retryInterval = DEFAULT_INTERVAL;
214                    }
215                } catch (final NumberFormatException nfe) {
216                    LOGGER.error("Interval " + interval + " is non-numeric. Using default");
217                    retryInterval = DEFAULT_INTERVAL;
218                }
219            }
220    
221            final boolean handleExceptions = suppress == null ? true : Boolean.valueOf(suppress);
222    
223            return new FailoverAppender(name, filter, primary, failovers, retryInterval, config, handleExceptions);
224        }
225    }