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.async;
18  
19  import java.util.Arrays;
20  import java.util.List;
21  import java.util.concurrent.TimeUnit;
22  
23  import org.apache.logging.log4j.Level;
24  import org.apache.logging.log4j.LogManager;
25  import org.apache.logging.log4j.core.Filter;
26  import org.apache.logging.log4j.core.LogEvent;
27  import org.apache.logging.log4j.core.config.AppenderRef;
28  import org.apache.logging.log4j.core.config.Configuration;
29  import org.apache.logging.log4j.core.config.LoggerConfig;
30  import org.apache.logging.log4j.core.config.Node;
31  import org.apache.logging.log4j.core.config.Property;
32  import org.apache.logging.log4j.core.config.plugins.Plugin;
33  import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
34  import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
35  import org.apache.logging.log4j.core.config.plugins.PluginElement;
36  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
37  import org.apache.logging.log4j.core.jmx.RingBufferAdmin;
38  import org.apache.logging.log4j.core.util.Booleans;
39  import org.apache.logging.log4j.util.Strings;
40  
41  /**
42   * Asynchronous Logger object that is created via configuration and can be
43   * combined with synchronous loggers.
44   * <p>
45   * AsyncLoggerConfig is a logger designed for high throughput and low latency
46   * logging. It does not perform any I/O in the calling (application) thread, but
47   * instead hands off the work to another thread as soon as possible. The actual
48   * logging is performed in the background thread. It uses the LMAX Disruptor
49   * library for inter-thread communication. (<a
50   * href="http://lmax-exchange.github.com/disruptor/"
51   * >http://lmax-exchange.github.com/disruptor/</a>)
52   * <p>
53   * To use AsyncLoggerConfig, specify {@code <asyncLogger>} or
54   * {@code <asyncRoot>} in configuration.
55   * <p>
56   * Note that for performance reasons, this logger does not include source
57   * location by default. You need to specify {@code includeLocation="true"} in
58   * the configuration or any %class, %location or %line conversion patterns in
59   * your log4j.xml configuration will produce either a "?" character or no output
60   * at all.
61   * <p>
62   * For best performance, use AsyncLoggerConfig with the RandomAccessFileAppender or
63   * RollingRandomAccessFileAppender, with immediateFlush=false. These appenders have
64   * built-in support for the batching mechanism used by the Disruptor library,
65   * and they will flush to disk at the end of each batch. This means that even
66   * with immediateFlush=false, there will never be any items left in the buffer;
67   * all log events will all be written to disk in a very efficient manner.
68   */
69  @Plugin(name = "asyncLogger", category = Node.CATEGORY, printObject = true)
70  public class AsyncLoggerConfig extends LoggerConfig {
71  
72      private final AsyncLoggerConfigDelegate delegate;
73  
74      protected AsyncLoggerConfig(final String name,
75              final List<AppenderRef> appenders, final Filter filter,
76              final Level level, final boolean additive,
77              final Property[] properties, final Configuration config,
78              final boolean includeLocation) {
79          super(name, appenders, filter, level, additive, properties, config,
80                  includeLocation);
81          delegate = config.getAsyncLoggerConfigDelegate();
82          delegate.setLogEventFactory(getLogEventFactory());
83      }
84  
85      /**
86       * Passes on the event to a separate thread that will call
87       * {@link #asyncCallAppenders(LogEvent)}.
88       */
89      @Override
90      protected void callAppenders(final LogEvent event) {
91          populateLazilyInitializedFields(event);
92  
93          if (!delegate.tryEnqueue(event, this)) {
94              final EventRoute eventRoute = delegate.getEventRoute(event.getLevel());
95              eventRoute.logMessage(this, event);
96          }
97      }
98  
99      private void populateLazilyInitializedFields(final LogEvent event) {
100         event.getSource();
101         event.getThreadName();
102     }
103 
104     void callAppendersInCurrentThread(final LogEvent event) {
105         super.callAppenders(event);
106     }
107 
108     void callAppendersInBackgroundThread(final LogEvent event) {
109         delegate.enqueueEvent(event, this);
110     }
111 
112     /** Called by AsyncLoggerConfigHelper.RingBufferLog4jEventHandler. */
113     void asyncCallAppenders(final LogEvent event) {
114         super.callAppenders(event);
115     }
116 
117     private String displayName() {
118         return LogManager.ROOT_LOGGER_NAME.equals(getName()) ? LoggerConfig.ROOT : getName();
119     }
120 
121     @Override
122     public void start() {
123         LOGGER.trace("AsyncLoggerConfig[{}] starting...", displayName());
124         super.start();
125     }
126 
127     @Override
128     public boolean stop(final long timeout, final TimeUnit timeUnit) {
129         setStopping();
130         super.stop(timeout, timeUnit, false);
131         LOGGER.trace("AsyncLoggerConfig[{}] stopping...", displayName());
132         setStopped();
133         return true;
134     }
135 
136     /**
137      * Creates and returns a new {@code RingBufferAdmin} that instruments the
138      * ringbuffer of this {@code AsyncLoggerConfig}.
139      *
140      * @param contextName name of the {@code LoggerContext}
141      * @return a new {@code RingBufferAdmin} that instruments the ringbuffer
142      */
143     public RingBufferAdmin createRingBufferAdmin(final String contextName) {
144         return delegate.createRingBufferAdmin(contextName, getName());
145     }
146 
147     /**
148      * Factory method to create a LoggerConfig.
149      *
150      * @param additivity True if additive, false otherwise.
151      * @param levelName The Level to be associated with the Logger.
152      * @param loggerName The name of the Logger.
153      * @param includeLocation "true" if location should be passed downstream
154      * @param refs An array of Appender names.
155      * @param properties Properties to pass to the Logger.
156      * @param config The Configuration.
157      * @param filter A Filter.
158      * @return A new LoggerConfig.
159      */
160     @PluginFactory
161     public static LoggerConfig createLogger(
162             @PluginAttribute("additivity") final String additivity,
163             @PluginAttribute("level") final String levelName,
164             @PluginAttribute("name") final String loggerName,
165             @PluginAttribute("includeLocation") final String includeLocation,
166             @PluginElement("AppenderRef") final AppenderRef[] refs,
167             @PluginElement("Properties") final Property[] properties,
168             @PluginConfiguration final Configuration config,
169             @PluginElement("Filter") final Filter filter) {
170         if (loggerName == null) {
171             LOGGER.error("Loggers cannot be configured without a name");
172             return null;
173         }
174 
175         final List<AppenderRef> appenderRefs = Arrays.asList(refs);
176         Level level;
177         try {
178             level = Level.toLevel(levelName, Level.ERROR);
179         } catch (final Exception ex) {
180             LOGGER.error(
181                     "Invalid Log level specified: {}. Defaulting to Error",
182                     levelName);
183             level = Level.ERROR;
184         }
185         final String name = loggerName.equals(LoggerConfig.ROOT) ? Strings.EMPTY : loggerName;
186         final boolean additive = Booleans.parseBoolean(additivity, true);
187 
188         return new AsyncLoggerConfig(name, appenderRefs, filter, level,
189                 additive, properties, config, includeLocation(includeLocation));
190     }
191 
192     // Note: for asynchronous loggers, includeLocation default is FALSE
193     protected static boolean includeLocation(final String includeLocationConfigValue) {
194         return Boolean.parseBoolean(includeLocationConfigValue);
195     }
196 
197     /**
198      * An asynchronous root Logger.
199      */
200     @Plugin(name = "asyncRoot", category = "Core", printObject = true)
201     public static class RootLogger extends LoggerConfig {
202 
203         @PluginFactory
204         public static LoggerConfig createLogger(
205                 @PluginAttribute("additivity") final String additivity,
206                 @PluginAttribute("level") final String levelName,
207                 @PluginAttribute("includeLocation") final String includeLocation,
208                 @PluginElement("AppenderRef") final AppenderRef[] refs,
209                 @PluginElement("Properties") final Property[] properties,
210                 @PluginConfiguration final Configuration config,
211                 @PluginElement("Filter") final Filter filter) {
212             final List<AppenderRef> appenderRefs = Arrays.asList(refs);
213             Level level;
214             try {
215                 level = Level.toLevel(levelName, Level.ERROR);
216             } catch (final Exception ex) {
217                 LOGGER.error(
218                         "Invalid Log level specified: {}. Defaulting to Error",
219                         levelName);
220                 level = Level.ERROR;
221             }
222             final boolean additive = Booleans.parseBoolean(additivity, true);
223 
224             return new AsyncLoggerConfig(LogManager.ROOT_LOGGER_NAME,
225                     appenderRefs, filter, level, additive, properties, config,
226                     AsyncLoggerConfig.includeLocation(includeLocation));
227         }
228     }
229 }