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