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