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.List;
20  
21  import org.apache.logging.log4j.Level;
22  import org.apache.logging.log4j.Marker;
23  import org.apache.logging.log4j.ThreadContext;
24  import org.apache.logging.log4j.ThreadContext.ContextStack;
25  import org.apache.logging.log4j.core.Logger;
26  import org.apache.logging.log4j.core.LoggerContext;
27  import org.apache.logging.log4j.core.config.Configuration;
28  import org.apache.logging.log4j.core.config.Property;
29  import org.apache.logging.log4j.core.config.ReliabilityStrategy;
30  import org.apache.logging.log4j.core.impl.ContextDataFactory;
31  import org.apache.logging.log4j.core.ContextDataInjector;
32  import org.apache.logging.log4j.core.impl.ContextDataInjectorFactory;
33  import org.apache.logging.log4j.core.util.Clock;
34  import org.apache.logging.log4j.core.util.ClockFactory;
35  import org.apache.logging.log4j.core.util.Constants;
36  import org.apache.logging.log4j.core.util.NanoClock;
37  import org.apache.logging.log4j.message.AsynchronouslyFormattable;
38  import org.apache.logging.log4j.message.Message;
39  import org.apache.logging.log4j.message.MessageFactory;
40  import org.apache.logging.log4j.message.ReusableMessage;
41  import org.apache.logging.log4j.util.StackLocatorUtil;
42  import org.apache.logging.log4j.util.StringMap;
43  import org.apache.logging.log4j.status.StatusLogger;
44  
45  import com.lmax.disruptor.EventTranslatorVararg;
46  import com.lmax.disruptor.dsl.Disruptor;
47  
48  /**
49   * AsyncLogger is a logger designed for high throughput and low latency logging. It does not perform any I/O in the
50   * calling (application) thread, but instead hands off the work to another thread as soon as possible. The actual
51   * logging is performed in the background thread. It uses the LMAX Disruptor library for inter-thread communication. (<a
52   * href="http://lmax-exchange.github.com/disruptor/" >http://lmax-exchange.github.com/disruptor/</a>)
53   * <p>
54   * To use AsyncLogger, specify the System property
55   * {@code -DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector} before you obtain a
56   * Logger, and all Loggers returned by LogManager.getLogger will be AsyncLoggers.
57   * <p>
58   * Note that for performance reasons, this logger does not include source location by default. You need to specify
59   * {@code includeLocation="true"} in the configuration or any %class, %location or %line conversion patterns in your
60   * log4j.xml configuration will produce either a "?" character or no output at all.
61   * <p>
62   * For best performance, use AsyncLogger with the RandomAccessFileAppender or RollingRandomAccessFileAppender, with
63   * immediateFlush=false. These appenders have 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 with immediateFlush=false, there will
65   * never be any items left in the buffer; all log events will all be written to disk in a very efficient manner.
66   */
67  public class AsyncLogger extends Logger implements EventTranslatorVararg<RingBufferLogEvent> {
68      // Implementation note: many methods in this class are tuned for performance. MODIFY WITH CARE!
69      // Specifically, try to keep the hot methods to 35 bytecodes or less:
70      // this is within the MaxInlineSize threshold and makes these methods candidates for
71      // immediate inlining instead of waiting until they are designated "hot enough".
72  
73      private static final StatusLogger LOGGER = StatusLogger.getLogger();
74      private static final Clock CLOCK = ClockFactory.getClock(); // not reconfigurable
75      private static final ContextDataInjector CONTEXT_DATA_INJECTOR = ContextDataInjectorFactory.createInjector();
76  
77      private static final ThreadNameCachingStrategy THREAD_NAME_CACHING_STRATEGY = ThreadNameCachingStrategy.create();
78  
79      private final ThreadLocal<RingBufferLogEventTranslator> threadLocalTranslator = new ThreadLocal<>();
80      private final AsyncLoggerDisruptor loggerDisruptor;
81  
82      private volatile boolean includeLocation; // reconfigurable
83      private volatile NanoClock nanoClock; // reconfigurable
84  
85      /**
86       * Constructs an {@code AsyncLogger} with the specified context, name and message factory.
87       *
88       * @param context context of this logger
89       * @param name name of this logger
90       * @param messageFactory message factory of this logger
91       * @param loggerDisruptor helper class that logging can be delegated to. This object owns the Disruptor.
92       */
93      public AsyncLogger(final LoggerContext context, final String name, final MessageFactory messageFactory,
94              final AsyncLoggerDisruptor loggerDisruptor) {
95          super(context, name, messageFactory);
96          this.loggerDisruptor = loggerDisruptor;
97          includeLocation = privateConfig.loggerConfig.isIncludeLocation();
98          nanoClock = context.getConfiguration().getNanoClock();
99      }
100 
101     /*
102      * (non-Javadoc)
103      *
104      * @see org.apache.logging.log4j.core.Logger#updateConfiguration(org.apache.logging.log4j.core.config.Configuration)
105      */
106     @Override
107     protected void updateConfiguration(final Configuration newConfig) {
108         nanoClock = newConfig.getNanoClock();
109         includeLocation = newConfig.getLoggerConfig(name).isIncludeLocation();
110         super.updateConfiguration(newConfig);
111     }
112 
113     // package protected for unit tests
114     NanoClock getNanoClock() {
115         return nanoClock;
116     }
117 
118     private RingBufferLogEventTranslator getCachedTranslator() {
119         RingBufferLogEventTranslator result = threadLocalTranslator.get();
120         if (result == null) {
121             result = new RingBufferLogEventTranslator();
122             threadLocalTranslator.set(result);
123         }
124         return result;
125     }
126 
127     @Override
128     public void logMessage(final String fqcn, final Level level, final Marker marker, final Message message,
129             final Throwable thrown) {
130 
131         if (loggerDisruptor.isUseThreadLocals()) {
132             logWithThreadLocalTranslator(fqcn, level, marker, message, thrown);
133         } else {
134             // LOG4J2-1172: avoid storing non-JDK classes in ThreadLocals to avoid memory leaks in web apps
135             logWithVarargTranslator(fqcn, level, marker, message, thrown);
136         }
137     }
138 
139     private boolean isReused(final Message message) {
140         return message instanceof ReusableMessage;
141     }
142 
143     /**
144      * Enqueues the specified log event data for logging in a background thread.
145      * <p>
146      * This re-uses a {@code RingBufferLogEventTranslator} instance cached in a {@code ThreadLocal} to avoid creating
147      * unnecessary objects with each event.
148      *
149      * @param fqcn fully qualified name of the caller
150      * @param level level at which the caller wants to log the message
151      * @param marker message marker
152      * @param message the log message
153      * @param thrown a {@code Throwable} or {@code null}
154      */
155     private void logWithThreadLocalTranslator(final String fqcn, final Level level, final Marker marker,
156             final Message message, final Throwable thrown) {
157         // Implementation note: this method is tuned for performance. MODIFY WITH CARE!
158 
159         final RingBufferLogEventTranslator translator = getCachedTranslator();
160         initTranslator(translator, fqcn, level, marker, message, thrown);
161         initTranslatorThreadValues(translator);
162         publish(translator);
163     }
164 
165     private void publish(final RingBufferLogEventTranslator translator) {
166         if (!loggerDisruptor.tryPublish(translator)) {
167             handleRingBufferFull(translator);
168         }
169     }
170 
171     private void handleRingBufferFull(final RingBufferLogEventTranslator translator) {
172         final EventRoute eventRoute = loggerDisruptor.getEventRoute(translator.level);
173         switch (eventRoute) {
174             case ENQUEUE:
175                 loggerDisruptor.enqueueLogMessageInfo(translator);
176                 break;
177             case SYNCHRONOUS:
178                 logMessageInCurrentThread(translator.fqcn, translator.level, translator.marker, translator.message,
179                         translator.thrown);
180                 break;
181             case DISCARD:
182                 break;
183             default:
184                 throw new IllegalStateException("Unknown EventRoute " + eventRoute);
185         }
186     }
187 
188     private void initTranslator(final RingBufferLogEventTranslator translator, final String fqcn,
189             final Level level, final Marker marker, final Message message, final Throwable thrown) {
190 
191         translator.setBasicValues(this, name, marker, fqcn, level, message, //
192                 // don't construct ThrowableProxy until required
193                 thrown,
194 
195                 // needs shallow copy to be fast (LOG4J2-154)
196                 ThreadContext.getImmutableStack(), //
197 
198                 // location (expensive to calculate)
199                 calcLocationIfRequested(fqcn), //
200                 CLOCK.currentTimeMillis(), //
201                 nanoClock.nanoTime() //
202         );
203     }
204 
205     private void initTranslatorThreadValues(final RingBufferLogEventTranslator translator) {
206         // constant check should be optimized out when using default (CACHED)
207         if (THREAD_NAME_CACHING_STRATEGY == ThreadNameCachingStrategy.UNCACHED) {
208             translator.updateThreadValues();
209         }
210     }
211 
212     /**
213      * Returns the caller location if requested, {@code null} otherwise.
214      *
215      * @param fqcn fully qualified caller name.
216      * @return the caller location if requested, {@code null} otherwise.
217      */
218     private StackTraceElement calcLocationIfRequested(final String fqcn) {
219         // location: very expensive operation. LOG4J2-153:
220         // Only include if "includeLocation=true" is specified,
221         // exclude if not specified or if "false" was specified.
222         return includeLocation ? StackLocatorUtil.calcLocation(fqcn) : null;
223     }
224 
225     /**
226      * Enqueues the specified log event data for logging in a background thread.
227      * <p>
228      * This creates a new varargs Object array for each invocation, but does not store any non-JDK classes in a
229      * {@code ThreadLocal} to avoid memory leaks in web applications (see LOG4J2-1172).
230      *
231      * @param fqcn fully qualified name of the caller
232      * @param level level at which the caller wants to log the message
233      * @param marker message marker
234      * @param message the log message
235      * @param thrown a {@code Throwable} or {@code null}
236      */
237     private void logWithVarargTranslator(final String fqcn, final Level level, final Marker marker,
238             final Message message, final Throwable thrown) {
239         // Implementation note: candidate for optimization: exceeds 35 bytecodes.
240 
241         final Disruptor<RingBufferLogEvent> disruptor = loggerDisruptor.getDisruptor();
242         if (disruptor == null) {
243             LOGGER.error("Ignoring log event after Log4j has been shut down.");
244             return;
245         }
246         // if the Message instance is reused, there is no point in freezing its message here
247         if (!canFormatMessageInBackground(message) && !isReused(message)) {
248             message.getFormattedMessage(); // LOG4J2-763: ask message to freeze parameters
249         }
250         // calls the translateTo method on this AsyncLogger
251         disruptor.getRingBuffer().publishEvent(this, this, calcLocationIfRequested(fqcn), fqcn, level, marker, message,
252                 thrown);
253     }
254 
255     private boolean canFormatMessageInBackground(final Message message) {
256         return Constants.FORMAT_MESSAGES_IN_BACKGROUND // LOG4J2-898: user wants to format all msgs in background
257                 || message.getClass().isAnnotationPresent(AsynchronouslyFormattable.class); // LOG4J2-1718
258     }
259 
260     /*
261      * (non-Javadoc)
262      *
263      * @see com.lmax.disruptor.EventTranslatorVararg#translateTo(java.lang.Object, long, java.lang.Object[])
264      */
265     @Override
266     public void translateTo(final RingBufferLogEvent event, final long sequence, final Object... args) {
267         // Implementation note: candidate for optimization: exceeds 35 bytecodes.
268         final AsyncLogger asyncLogger = (AsyncLogger) args[0];
269         final StackTraceElement location = (StackTraceElement) args[1];
270         final String fqcn = (String) args[2];
271         final Level level = (Level) args[3];
272         final Marker marker = (Marker) args[4];
273         final Message message = (Message) args[5];
274         final Throwable thrown = (Throwable) args[6];
275 
276         // needs shallow copy to be fast (LOG4J2-154)
277         final ContextStack contextStack = ThreadContext.getImmutableStack();
278 
279         final Thread currentThread = Thread.currentThread();
280         final String threadName = THREAD_NAME_CACHING_STRATEGY.getThreadName();
281         event.setValues(asyncLogger, asyncLogger.getName(), marker, fqcn, level, message, thrown,
282                 // config properties are taken care of in the EventHandler thread
283                 // in the AsyncLogger#actualAsyncLog method
284                 CONTEXT_DATA_INJECTOR.injectContextData(null, (StringMap) event.getContextData()),
285                 contextStack, currentThread.getId(), threadName, currentThread.getPriority(), location,
286                 CLOCK.currentTimeMillis(), nanoClock.nanoTime());
287     }
288 
289     /**
290      * LOG4J2-471: prevent deadlock when RingBuffer is full and object being logged calls Logger.log() from its
291      * toString() method
292      *
293      * @param fqcn fully qualified caller name
294      * @param level log level
295      * @param marker optional marker
296      * @param message log message
297      * @param thrown optional exception
298      */
299     void logMessageInCurrentThread(final String fqcn, final Level level, final Marker marker,
300             final Message message, final Throwable thrown) {
301         // bypass RingBuffer and invoke Appender directly
302         final ReliabilityStrategy strategy = privateConfig.loggerConfig.getReliabilityStrategy();
303         strategy.log(this, getName(), fqcn, marker, level, message, thrown);
304     }
305 
306     /**
307      * This method is called by the EventHandler that processes the RingBufferLogEvent in a separate thread.
308      * Merges the contents of the configuration map into the contextData, after replacing any variables in the property
309      * values with the StrSubstitutor-supplied actual values.
310      *
311      * @param event the event to log
312      */
313     public void actualAsyncLog(final RingBufferLogEvent event) {
314         final List<Property> properties = privateConfig.loggerConfig.getPropertyList();
315 
316         if (properties != null) {
317             StringMap contextData = (StringMap) event.getContextData();
318             if (contextData.isFrozen()) {
319                 final StringMap temp = ContextDataFactory.createContextData();
320                 temp.putAll(contextData);
321                 contextData = temp;
322             }
323             for (int i = 0; i < properties.size(); i++) {
324                 final Property prop = properties.get(i);
325                 if (contextData.getValue(prop.getName()) != null) {
326                     continue; // contextMap overrides config properties
327                 }
328                 final String value = prop.isValueNeedsLookup() //
329                         ? privateConfig.config.getStrSubstitutor().replace(event, prop.getValue()) //
330                         : prop.getValue();
331                 contextData.putValue(prop.getName(), value);
332             }
333             event.setContextData(contextData);
334         }
335 
336         final ReliabilityStrategy strategy = privateConfig.loggerConfig.getReliabilityStrategy();
337         strategy.log(this, event);
338     }
339 }