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.util.StringMap;
032
033/**
034 * Garbage-free LogEventFactory that reuses a single mutable log event.
035 * @since 2.6
036 */
037public class ReusableLogEventFactory implements LogEventFactory, LocationAwareLogEventFactory {
038    private static final ThreadNameCachingStrategy THREAD_NAME_CACHING_STRATEGY = ThreadNameCachingStrategy.create();
039    private static final Clock CLOCK = ClockFactory.getClock();
040
041    private static final ThreadLocal<MutableLogEvent> mutableLogEventThreadLocal = new ThreadLocal<>();
042    private final ContextDataInjector injector = ContextDataInjectorFactory.createInjector();
043
044    /**
045     * Creates a log event.
046     *
047     * @param loggerName The name of the Logger.
048     * @param marker An optional Marker.
049     * @param fqcn The fully qualified class name of the caller.
050     * @param level The event Level.
051     * @param message The Message.
052     * @param properties Properties to be added to the log event.
053     * @param t An optional Throwable.
054     * @return The LogEvent.
055     */
056    @Override
057    public LogEvent createEvent(final String loggerName, final Marker marker,
058        final String fqcn, final Level level, final Message message,
059        final List<Property> properties, final Throwable t) {
060        return createEvent(loggerName, marker, fqcn, null, level, message, properties, t);
061    }
062
063    /**
064     * Creates a log event.
065     *
066     * @param loggerName The name of the Logger.
067     * @param marker An optional Marker.
068     * @param fqcn The fully qualified class name of the caller.
069     * @param location The location of the caller.
070     * @param level The event Level.
071     * @param message The Message.
072     * @param properties Properties to be added to the log event.
073     * @param t An optional Throwable.
074     * @return The LogEvent.
075     */
076    @Override
077    public LogEvent createEvent(final String loggerName, final Marker marker, final String fqcn,
078                                final StackTraceElement location, final Level level, final Message message,
079                                final List<Property> properties, final Throwable t) {
080        MutableLogEvent result = getOrCreateMutableLogEvent();
081        result.reserved = true;
082        // No need to clear here, values are cleared in release when reserved is set to false.
083        // If the event was dirty we'd create a new one.
084
085        result.setLoggerName(loggerName);
086        result.setMarker(marker);
087        result.setLoggerFqcn(fqcn);
088        result.setLevel(level == null ? Level.OFF : level);
089        result.setMessage(message);
090        result.initTime(CLOCK, Log4jLogEvent.getNanoClock());
091        result.setThrown(t);
092        result.setSource(location);
093        result.setContextData(injector.injectContextData(properties, (StringMap) result.getContextData()));
094        result.setContextStack(ThreadContext.getDepth() == 0 ? ThreadContext.EMPTY_STACK : ThreadContext.cloneStack());// mutable copy
095
096        if (THREAD_NAME_CACHING_STRATEGY == ThreadNameCachingStrategy.UNCACHED) {
097            result.setThreadName(Thread.currentThread().getName()); // Thread.getName() allocates Objects on each call
098            result.setThreadPriority(Thread.currentThread().getPriority());
099        }
100        return result;
101    }
102
103    private static MutableLogEvent getOrCreateMutableLogEvent() {
104        MutableLogEvent result = mutableLogEventThreadLocal.get();
105        return result == null || result.reserved ? createInstance(result) : result;
106    }
107
108    private static MutableLogEvent createInstance(MutableLogEvent existing) {
109        MutableLogEvent result = new MutableLogEvent();
110
111        // usually no need to re-initialize thread-specific fields since the event is stored in a ThreadLocal
112        result.setThreadId(Thread.currentThread().getId());
113        result.setThreadName(Thread.currentThread().getName()); // Thread.getName() allocates Objects on each call
114        result.setThreadPriority(Thread.currentThread().getPriority());
115        if (existing == null) {
116            mutableLogEventThreadLocal.set(result);
117        }
118        return result;
119    }
120
121    /**
122     * Switches the {@code reserved} flag off if the specified event is a MutableLogEvent, otherwise does nothing.
123     * This flag is used internally to verify that a reusable log event is no longer in use and can be reused.
124     * @param logEvent the log event to make available again
125     * @since 2.7
126     */
127    public static void release(final LogEvent logEvent) { // LOG4J2-1583
128        if (logEvent instanceof MutableLogEvent) {
129            final MutableLogEvent mutableLogEvent = (MutableLogEvent) logEvent;
130            mutableLogEvent.clear();
131            mutableLogEvent.reserved = false;
132        }
133    }
134}