001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.core.impl;
018
019import java.util.List;
020
021import org.apache.logging.log4j.Level;
022import org.apache.logging.log4j.Marker;
023import org.apache.logging.log4j.ThreadContext;
024import org.apache.logging.log4j.core.ContextDataInjector;
025import org.apache.logging.log4j.core.LogEvent;
026import org.apache.logging.log4j.core.async.ThreadNameCachingStrategy;
027import org.apache.logging.log4j.core.config.Property;
028import org.apache.logging.log4j.core.util.Clock;
029import org.apache.logging.log4j.core.util.ClockFactory;
030import org.apache.logging.log4j.message.Message;
031import org.apache.logging.log4j.message.TimestampMessage;
032import org.apache.logging.log4j.util.StringMap;
033
034/**
035 * Garbage-free LogEventFactory that reuses a single mutable log event.
036 * @since 2.6
037 */
038public class ReusableLogEventFactory implements LogEventFactory {
039    private static final ThreadNameCachingStrategy THREAD_NAME_CACHING_STRATEGY = ThreadNameCachingStrategy.create();
040    private static final Clock CLOCK = ClockFactory.getClock();
041
042    private static ThreadLocal<MutableLogEvent> mutableLogEventThreadLocal = new ThreadLocal<>();
043    private final ContextDataInjector injector = ContextDataInjectorFactory.createInjector();
044
045    /**
046     * Creates a log event.
047     *
048     * @param loggerName The name of the Logger.
049     * @param marker An optional Marker.
050     * @param fqcn The fully qualified class name of the caller.
051     * @param level The event Level.
052     * @param message The Message.
053     * @param properties Properties to be added to the log event.
054     * @param t An optional Throwable.
055     * @return The LogEvent.
056     */
057    @Override
058    public LogEvent createEvent(final String loggerName, final Marker marker,
059                                final String fqcn, final Level level, final Message message,
060                                final List<Property> properties, final Throwable t) {
061        MutableLogEvent result = mutableLogEventThreadLocal.get();
062        if (result == null || result.reserved) {
063            final boolean initThreadLocal = result == null;
064            result = new MutableLogEvent();
065
066            // usually no need to re-initialize thread-specific fields since the event is stored in a ThreadLocal
067            result.setThreadId(Thread.currentThread().getId());
068            result.setThreadName(Thread.currentThread().getName()); // Thread.getName() allocates Objects on each call
069            result.setThreadPriority(Thread.currentThread().getPriority());
070            if (initThreadLocal) {
071                mutableLogEventThreadLocal.set(result);
072            }
073        }
074        result.reserved = true;
075        result.clear(); // ensure any previously cached values (thrownProxy, source, etc.) are cleared
076
077        result.setLoggerName(loggerName);
078        result.setMarker(marker);
079        result.setLoggerFqcn(fqcn);
080        result.setLevel(level == null ? Level.OFF : level);
081        result.setMessage(message);
082        result.setThrown(t);
083        result.setContextData(injector.injectContextData(properties, (StringMap) result.getContextData()));
084        result.setContextStack(ThreadContext.getDepth() == 0 ? ThreadContext.EMPTY_STACK : ThreadContext.cloneStack());// mutable copy
085        result.setTimeMillis(message instanceof TimestampMessage
086                ? ((TimestampMessage) message).getTimestamp()
087                : CLOCK.currentTimeMillis());
088        result.setNanoTime(Log4jLogEvent.getNanoClock().nanoTime());
089
090        if (THREAD_NAME_CACHING_STRATEGY == ThreadNameCachingStrategy.UNCACHED) {
091            result.setThreadName(Thread.currentThread().getName()); // Thread.getName() allocates Objects on each call
092            result.setThreadPriority(Thread.currentThread().getPriority());
093        }
094        return result;
095    }
096
097    /**
098     * Switches the {@code reserved} flag off if the specified event is a MutableLogEvent, otherwise does nothing.
099     * 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}