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.impl;
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.core.ContextDataInjector;
25  import org.apache.logging.log4j.core.LogEvent;
26  import org.apache.logging.log4j.core.async.ThreadNameCachingStrategy;
27  import org.apache.logging.log4j.core.config.Property;
28  import org.apache.logging.log4j.core.util.Clock;
29  import org.apache.logging.log4j.core.util.ClockFactory;
30  import org.apache.logging.log4j.message.Message;
31  import org.apache.logging.log4j.message.TimestampMessage;
32  import org.apache.logging.log4j.util.StringMap;
33  
34  /**
35   * Garbage-free LogEventFactory that reuses a single mutable log event.
36   * @since 2.6
37   */
38  public class ReusableLogEventFactory implements LogEventFactory {
39      private static final ThreadNameCachingStrategy THREAD_NAME_CACHING_STRATEGY = ThreadNameCachingStrategy.create();
40      private static final Clock CLOCK = ClockFactory.getClock();
41  
42      private static ThreadLocal<MutableLogEvent> mutableLogEventThreadLocal = new ThreadLocal<>();
43      private final ContextDataInjector injector = ContextDataInjectorFactory.createInjector();
44  
45      /**
46       * Creates a log event.
47       *
48       * @param loggerName The name of the Logger.
49       * @param marker An optional Marker.
50       * @param fqcn The fully qualified class name of the caller.
51       * @param level The event Level.
52       * @param message The Message.
53       * @param properties Properties to be added to the log event.
54       * @param t An optional Throwable.
55       * @return The LogEvent.
56       */
57      @Override
58      public LogEvent createEvent(final String loggerName, final Marker marker,
59                                  final String fqcn, final Level level, final Message message,
60                                  final List<Property> properties, final Throwable t) {
61          MutableLogEvent result = mutableLogEventThreadLocal.get();
62          if (result == null || result.reserved) {
63              final boolean initThreadLocal = result == null;
64              result = new MutableLogEvent();
65  
66              // usually no need to re-initialize thread-specific fields since the event is stored in a ThreadLocal
67              result.setThreadId(Thread.currentThread().getId());
68              result.setThreadName(Thread.currentThread().getName()); // Thread.getName() allocates Objects on each call
69              result.setThreadPriority(Thread.currentThread().getPriority());
70              if (initThreadLocal) {
71                  mutableLogEventThreadLocal.set(result);
72              }
73          }
74          result.reserved = true;
75          result.clear(); // ensure any previously cached values (thrownProxy, source, etc.) are cleared
76  
77          result.setLoggerName(loggerName);
78          result.setMarker(marker);
79          result.setLoggerFqcn(fqcn);
80          result.setLevel(level == null ? Level.OFF : level);
81          result.setMessage(message);
82          result.setThrown(t);
83          result.setContextData(injector.injectContextData(properties, (StringMap) result.getContextData()));
84          result.setContextStack(ThreadContext.getDepth() == 0 ? ThreadContext.EMPTY_STACK : ThreadContext.cloneStack());// mutable copy
85          result.setTimeMillis(message instanceof TimestampMessage
86                  ? ((TimestampMessage) message).getTimestamp()
87                  : CLOCK.currentTimeMillis());
88          result.setNanoTime(Log4jLogEvent.getNanoClock().nanoTime());
89  
90          if (THREAD_NAME_CACHING_STRATEGY == ThreadNameCachingStrategy.UNCACHED) {
91              result.setThreadName(Thread.currentThread().getName()); // Thread.getName() allocates Objects on each call
92              result.setThreadPriority(Thread.currentThread().getPriority());
93          }
94          return result;
95      }
96  
97      /**
98       * Switches the {@code reserved} flag off if the specified event is a MutableLogEvent, otherwise does nothing.
99       * This flag is used internally to verify that a reusable log event is no longer in use and can be reused.
100      * @param logEvent the log event to make available again
101      * @since 2.7
102      */
103     public static void release(final LogEvent logEvent) { // LOG4J2-1583
104         if (logEvent instanceof MutableLogEvent) {
105             ((MutableLogEvent) logEvent).reserved = false;
106         }
107     }
108 }