View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.core.appender;
18  
19  import java.util.ArrayList;
20  import java.util.List;
21  import java.util.Map;
22  import java.util.concurrent.TimeUnit;
23  
24  import org.apache.logging.log4j.LoggingException;
25  import org.apache.logging.log4j.core.Appender;
26  import org.apache.logging.log4j.core.Filter;
27  import org.apache.logging.log4j.core.LogEvent;
28  import org.apache.logging.log4j.core.config.AppenderControl;
29  import org.apache.logging.log4j.core.config.Configuration;
30  import org.apache.logging.log4j.core.config.plugins.Plugin;
31  import org.apache.logging.log4j.core.config.plugins.PluginAliases;
32  import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
33  import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
34  import org.apache.logging.log4j.core.config.plugins.PluginElement;
35  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
36  import org.apache.logging.log4j.core.util.Booleans;
37  import org.apache.logging.log4j.core.util.Constants;
38  
39  /**
40   * The FailoverAppender will capture exceptions in an Appender and then route the event
41   * to a different appender. Hopefully it is obvious that the Appenders must be configured
42   * to not suppress exceptions for the FailoverAppender to work.
43   */
44  @Plugin(name = "Failover", category = "Core", elementType = "appender", printObject = true)
45  public final class FailoverAppender extends AbstractAppender {
46  
47      private static final long serialVersionUID = 1L;
48  
49      private static final int DEFAULT_INTERVAL_SECONDS = 60;
50  
51      private final String primaryRef;
52  
53      private final String[] failovers;
54  
55      private final Configuration config;
56  
57      private AppenderControl primary;
58  
59      private final List<AppenderControl> failoverAppenders = new ArrayList<>();
60  
61      private final long intervalNanos;
62  
63      private volatile long nextCheckNanos = 0;
64  
65      private FailoverAppender(final String name, final Filter filter, final String primary, final String[] failovers,
66                               final int intervalMillis, final Configuration config, final boolean ignoreExceptions) {
67          super(name, filter, null, ignoreExceptions);
68          this.primaryRef = primary;
69          this.failovers = failovers;
70          this.config = config;
71          this.intervalNanos = TimeUnit.MILLISECONDS.toNanos(intervalMillis);
72      }
73  
74  
75      @Override
76      public void start() {
77          final Map<String, Appender> map = config.getAppenders();
78          int errors = 0;
79          final Appender appender = map.get(primaryRef);
80          if (appender != null) {
81              primary = new AppenderControl(appender, null, null);
82          } else {
83              LOGGER.error("Unable to locate primary Appender " + primaryRef);
84              ++errors;
85          }
86          for (final String name : failovers) {
87              final Appender foAppender = map.get(name);
88              if (foAppender != null) {
89                  failoverAppenders.add(new AppenderControl(foAppender, null, null));
90              } else {
91                  LOGGER.error("Failover appender " + name + " is not configured");
92              }
93          }
94          if (failoverAppenders.isEmpty()) {
95              LOGGER.error("No failover appenders are available");
96              ++errors;
97          }
98          if (errors == 0) {
99              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 }