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