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