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;
022import java.util.concurrent.TimeUnit;
023
024import org.apache.logging.log4j.LoggingException;
025import org.apache.logging.log4j.core.Appender;
026import org.apache.logging.log4j.core.Filter;
027import org.apache.logging.log4j.core.LogEvent;
028import org.apache.logging.log4j.core.config.AppenderControl;
029import org.apache.logging.log4j.core.config.Configuration;
030import org.apache.logging.log4j.core.config.plugins.Plugin;
031import org.apache.logging.log4j.core.config.plugins.PluginAliases;
032import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
033import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
034import org.apache.logging.log4j.core.config.plugins.PluginElement;
035import org.apache.logging.log4j.core.config.plugins.PluginFactory;
036import org.apache.logging.log4j.core.util.Booleans;
037import org.apache.logging.log4j.core.util.Constants;
038
039/**
040 * The FailoverAppender will capture exceptions in an Appender and then route the event
041 * to a different appender. Hopefully it is obvious that the Appenders must be configured
042 * to not suppress exceptions for the FailoverAppender to work.
043 */
044@Plugin(name = "Failover", category = "Core", elementType = "appender", printObject = true)
045public final class FailoverAppender extends AbstractAppender {
046
047    private static final long serialVersionUID = 1L;
048
049    private static final int DEFAULT_INTERVAL_SECONDS = 60;
050
051    private final String primaryRef;
052
053    private final String[] failovers;
054
055    private final Configuration config;
056
057    private AppenderControl primary;
058
059    private final List<AppenderControl> failoverAppenders = new ArrayList<>();
060
061    private final long intervalNanos;
062
063    private volatile long nextCheckNanos = 0;
064
065    private FailoverAppender(final String name, final Filter filter, final String primary, final String[] failovers,
066                             final int intervalMillis, final Configuration config, final boolean ignoreExceptions) {
067        super(name, filter, null, ignoreExceptions);
068        this.primaryRef = primary;
069        this.failovers = failovers;
070        this.config = config;
071        this.intervalNanos = TimeUnit.MILLISECONDS.toNanos(intervalMillis);
072    }
073
074
075    @Override
076    public void start() {
077        final Map<String, Appender> map = config.getAppenders();
078        int errors = 0;
079        final Appender appender = map.get(primaryRef);
080        if (appender != null) {
081            primary = new AppenderControl(appender, null, null);
082        } else {
083            LOGGER.error("Unable to locate primary Appender " + primaryRef);
084            ++errors;
085        }
086        for (final String name : failovers) {
087            final Appender foAppender = map.get(name);
088            if (foAppender != null) {
089                failoverAppenders.add(new AppenderControl(foAppender, null, null));
090            } else {
091                LOGGER.error("Failover appender " + name + " is not configured");
092            }
093        }
094        if (failoverAppenders.isEmpty()) {
095            LOGGER.error("No failover appenders are available");
096            ++errors;
097        }
098        if (errors == 0) {
099            super.start();
100        }
101    }
102
103    /**
104     * Handle the Log event.
105     * @param event The LogEvent.
106     */
107    @Override
108    public void append(final LogEvent event) {
109        if (!isStarted()) {
110            error("FailoverAppender " + getName() + " did not start successfully");
111            return;
112        }
113        final long localCheckNanos = nextCheckNanos;
114        if (localCheckNanos == 0 || System.nanoTime() - localCheckNanos > 0) {
115            callAppender(event);
116        } else {
117            failover(event, null);
118        }
119    }
120
121    private void callAppender(final LogEvent event) {
122        try {
123            primary.callAppender(event);
124            nextCheckNanos = 0;
125        } catch (final Exception ex) {
126            nextCheckNanos = System.nanoTime() + intervalNanos;
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            }
151            throw new LoggingException("Unable to write to failover appenders", failoverException);
152        }
153    }
154
155    @Override
156    public String toString() {
157        final StringBuilder sb = new StringBuilder(getName());
158        sb.append(" primary=").append(primary).append(", failover={");
159        boolean first = true;
160        for (final String str : failovers) {
161            if (!first) {
162                sb.append(", ");
163            }
164            sb.append(str);
165            first = false;
166        }
167        sb.append('}');
168        return sb.toString();
169    }
170
171    /**
172     * Create a Failover Appender.
173     * @param name The name of the Appender (required).
174     * @param primary The name of the primary Appender (required).
175     * @param failovers The name of one or more Appenders to fail over to (at least one is required).
176     * @param retryIntervalSeconds The retry interval in seconds.
177     * @param config The current Configuration (passed by the Configuration when the appender is created).
178     * @param filter A Filter (optional).
179     * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise
180     *               they are propagated to the caller.
181     * @return The FailoverAppender that was created.
182     */
183    @PluginFactory
184    public static FailoverAppender createAppender(
185            @PluginAttribute("name") final String name,
186            @PluginAttribute("primary") final String primary,
187            @PluginElement("Failovers") final String[] failovers,
188            @PluginAliases("retryInterval") // deprecated
189            @PluginAttribute("retryIntervalSeconds") final String retryIntervalSeconds,
190            @PluginConfiguration final Configuration config,
191            @PluginElement("Filter") 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(retryIntervalSeconds, DEFAULT_INTERVAL_SECONDS);
207        int retryIntervalMillis;
208        if (seconds >= 0) {
209            retryIntervalMillis = seconds * Constants.MILLIS_IN_SECONDS;
210        } else {
211            LOGGER.warn("Interval " + retryIntervalSeconds + " 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}