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.routing;
18  
19  import org.apache.logging.log4j.core.Appender;
20  import org.apache.logging.log4j.core.Filter;
21  import org.apache.logging.log4j.core.LogEvent;
22  import org.apache.logging.log4j.core.appender.AbstractAppender;
23  import org.apache.logging.log4j.core.appender.rewrite.RewritePolicy;
24  import org.apache.logging.log4j.core.config.AppenderControl;
25  import org.apache.logging.log4j.core.config.Configuration;
26  import org.apache.logging.log4j.core.config.Node;
27  import org.apache.logging.log4j.core.config.plugins.Plugin;
28  import org.apache.logging.log4j.core.config.plugins.PluginAttr;
29  import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
30  import org.apache.logging.log4j.core.config.plugins.PluginElement;
31  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
32  
33  import java.io.Serializable;
34  import java.util.Map;
35  import java.util.concurrent.ConcurrentHashMap;
36  import java.util.concurrent.ConcurrentMap;
37  
38  /**
39   * This Appender "routes" between various Appenders, some of which can be references to
40   * Appenders defined earlier in the configuration while others can be dynamically created
41   * within this Appender as required. Routing is achieved by specifying a pattern on
42   * the Routing appender declaration. The pattern should contain one or more substitution patterns of
43   * the form "$${[key:]token}". The pattern will be resolved each time the Appender is called using
44   * the built in StrSubstitutor and the StrLookup plugin that matches the specified key.
45   */
46  @Plugin(name = "Routing", category = "Core", elementType = "appender", printObject = true)
47  public final class RoutingAppender<T extends Serializable> extends AbstractAppender<T> {
48      private static final String DEFAULT_KEY = "ROUTING_APPENDER_DEFAULT";
49      private final Routes routes;
50      private final Route defaultRoute;
51      private final Configuration config;
52      private final ConcurrentMap<String, AppenderControl<T>> appenders =
53              new ConcurrentHashMap<String, AppenderControl<T>>();
54      private final RewritePolicy rewritePolicy;
55  
56      private RoutingAppender(final String name, final Filter filter, final boolean handleException, final Routes routes,
57                              final RewritePolicy rewritePolicy, final Configuration config) {
58          super(name, filter, null, handleException);
59          this.routes = routes;
60          this.config = config;
61          this.rewritePolicy = rewritePolicy;
62          Route defRoute = null;
63          for (final Route route : routes.getRoutes()) {
64              if (route.getKey() == null) {
65                  if (defRoute == null) {
66                      defRoute = route;
67                  } else {
68                      error("Multiple default routes. Route " + route.toString() + " will be ignored");
69                  }
70              }
71          }
72          defaultRoute = defRoute;
73      }
74  
75      @Override
76      @SuppressWarnings("unchecked")
77      public void start() {
78          final Map<String, Appender<?>> map = config.getAppenders();
79          // Register all the static routes.
80          for (final Route route : routes.getRoutes()) {
81              if (route.getAppenderRef() != null) {
82                  final Appender<?> appender = map.get(route.getAppenderRef());
83                  if (appender != null) {
84                      final String key = route == defaultRoute ? DEFAULT_KEY : route.getKey();
85                      appenders.put(key, new AppenderControl(appender, null, null));
86                  } else {
87                      LOGGER.error("Appender " + route.getAppenderRef() + " cannot be located. Route ignored");
88                  }
89              }
90          }
91          super.start();
92      }
93  
94      @Override
95      public void stop() {
96          super.stop();
97          final Map<String, Appender<?>> map = config.getAppenders();
98          for (final Map.Entry<String, AppenderControl<T>> entry : appenders.entrySet()) {
99              final String name = entry.getValue().getAppender().getName();
100             if (!map.containsKey(name)) {
101                 entry.getValue().getAppender().stop();
102             }
103         }
104     }
105 
106     @Override
107     public void append(LogEvent event) {
108         if (rewritePolicy != null) {
109             event = rewritePolicy.rewrite(event);
110         }
111         final String key = config.getSubst().replace(event, routes.getPattern());
112         final AppenderControl<T> control = getControl(key, event);
113         if (control != null) {
114             control.callAppender(event);
115         }
116     }
117 
118     private synchronized AppenderControl<T> getControl(final String key, final LogEvent event) {
119         AppenderControl<T> control = appenders.get(key);
120         if (control != null) {
121             return control;
122         }
123         Route route = null;
124         for (final Route r : routes.getRoutes()) {
125             if (r.getAppenderRef() == null && key.equals(r.getKey())) {
126                 route = r;
127                 break;
128             }
129         }
130         if (route == null) {
131             route = defaultRoute;
132         }
133         if (route != null) {
134             final Appender<T> app = createAppender(route, event);
135             if (app == null) {
136                 return null;
137             }
138             control = new AppenderControl<T>(app, null, null);
139             appenders.put(key, control);
140         }
141 
142         return control;
143     }
144 
145     private Appender<T> createAppender(final Route route, final LogEvent event) {
146         final Node routeNode = route.getNode();
147         for (final Node node : routeNode.getChildren()) {
148             if (node.getType().getElementName().equals("appender")) {
149                 final Node appNode = new Node(node);
150                 config.createConfiguration(appNode, event);
151                 if (appNode.getObject() instanceof Appender) {
152                     @SuppressWarnings("unchecked")
153                     final Appender<T> app = (Appender<T>) appNode.getObject();
154                     app.start();
155                     return app;
156                 }
157                 LOGGER.error("Unable to create Appender of type " + node.getName());
158                 return null;
159             }
160         }
161         LOGGER.error("No Appender was configured for route " + route.getKey());
162         return null;
163     }
164 
165     /**
166      * Create a RoutingAppender.
167      * @param name The name of the Appender.
168      * @param suppress "true" if exceptions should be hidden from the application, "false" otherwise.
169      * The default is "true".
170      * @param routes The routing definitions.
171      * @param config The Configuration (automatically added by the Configuration).
172      * @param rewritePolicy A RewritePolicy, if any.
173      * @param filter A Filter to restrict events processed by the Appender or null.
174      * @return The RoutingAppender
175      */
176     @PluginFactory
177     public static <S extends Serializable> RoutingAppender<S> createAppender(@PluginAttr("name") final String name,
178                                           @PluginAttr("suppressExceptions") final String suppress,
179                                           @PluginElement("routes") final Routes routes,
180                                           @PluginConfiguration final Configuration config,
181                                           @PluginElement("rewritePolicy") final RewritePolicy rewritePolicy,
182                                           @PluginElement("filters") final Filter filter) {
183 
184         final boolean handleExceptions = suppress == null ? true : Boolean.valueOf(suppress);
185 
186         if (name == null) {
187             LOGGER.error("No name provided for RoutingAppender");
188             return null;
189         }
190         if (routes == null) {
191             LOGGER.error("No routes defined for RoutingAppender");
192             return null;
193         }
194         return new RoutingAppender<S>(name, filter, handleExceptions, routes, rewritePolicy, config);
195     }
196 }