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