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.async;
018
019import java.util.Arrays;
020import java.util.List;
021import java.util.concurrent.TimeUnit;
022
023import org.apache.logging.log4j.Level;
024import org.apache.logging.log4j.LogManager;
025import org.apache.logging.log4j.core.Filter;
026import org.apache.logging.log4j.core.LogEvent;
027import org.apache.logging.log4j.core.config.AppenderRef;
028import org.apache.logging.log4j.core.config.Configuration;
029import org.apache.logging.log4j.core.config.LoggerConfig;
030import org.apache.logging.log4j.core.config.Node;
031import org.apache.logging.log4j.core.config.Property;
032import org.apache.logging.log4j.core.config.plugins.Plugin;
033import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
034import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
035import org.apache.logging.log4j.core.config.plugins.PluginElement;
036import org.apache.logging.log4j.core.config.plugins.PluginFactory;
037import org.apache.logging.log4j.core.jmx.RingBufferAdmin;
038import org.apache.logging.log4j.core.util.Booleans;
039import org.apache.logging.log4j.util.Strings;
040
041/**
042 * Asynchronous Logger object that is created via configuration and can be
043 * combined with synchronous loggers.
044 * <p>
045 * AsyncLoggerConfig is a logger designed for high throughput and low latency
046 * logging. It does not perform any I/O in the calling (application) thread, but
047 * instead hands off the work to another thread as soon as possible. The actual
048 * logging is performed in the background thread. It uses the LMAX Disruptor
049 * library for inter-thread communication. (<a
050 * href="http://lmax-exchange.github.com/disruptor/"
051 * >http://lmax-exchange.github.com/disruptor/</a>)
052 * <p>
053 * To use AsyncLoggerConfig, specify {@code <asyncLogger>} or
054 * {@code <asyncRoot>} in configuration.
055 * <p>
056 * Note that for performance reasons, this logger does not include source
057 * location by default. You need to specify {@code includeLocation="true"} in
058 * the configuration or any %class, %location or %line conversion patterns in
059 * your log4j.xml configuration will produce either a "?" character or no output
060 * at all.
061 * <p>
062 * For best performance, use AsyncLoggerConfig with the RandomAccessFileAppender or
063 * RollingRandomAccessFileAppender, with immediateFlush=false. These appenders have
064 * built-in support for the batching mechanism used by the Disruptor library,
065 * and they will flush to disk at the end of each batch. This means that even
066 * with immediateFlush=false, there will never be any items left in the buffer;
067 * all log events will all be written to disk in a very efficient manner.
068 */
069@Plugin(name = "asyncLogger", category = Node.CATEGORY, printObject = true)
070public class AsyncLoggerConfig extends LoggerConfig {
071
072    private final AsyncLoggerConfigDelegate delegate;
073
074    protected AsyncLoggerConfig(final String name,
075            final List<AppenderRef> appenders, final Filter filter,
076            final Level level, final boolean additive,
077            final Property[] properties, final Configuration config,
078            final boolean includeLocation) {
079        super(name, appenders, filter, level, additive, properties, config,
080                includeLocation);
081        delegate = config.getAsyncLoggerConfigDelegate();
082        delegate.setLogEventFactory(getLogEventFactory());
083    }
084
085    /**
086     * Passes on the event to a separate thread that will call
087     * {@link #asyncCallAppenders(LogEvent)}.
088     */
089    @Override
090    protected void callAppenders(final LogEvent event) {
091        populateLazilyInitializedFields(event);
092
093        if (!delegate.tryEnqueue(event, this)) {
094            final EventRoute eventRoute = delegate.getEventRoute(event.getLevel());
095            eventRoute.logMessage(this, event);
096        }
097    }
098
099    private void populateLazilyInitializedFields(final LogEvent event) {
100        event.getSource();
101        event.getThreadName();
102    }
103
104    void callAppendersInCurrentThread(final LogEvent event) {
105        super.callAppenders(event);
106    }
107
108    void callAppendersInBackgroundThread(final LogEvent event) {
109        delegate.enqueueEvent(event, this);
110    }
111
112    /** Called by AsyncLoggerConfigHelper.RingBufferLog4jEventHandler. */
113    void asyncCallAppenders(final LogEvent event) {
114        super.callAppenders(event);
115    }
116
117    private String displayName() {
118        return LogManager.ROOT_LOGGER_NAME.equals(getName()) ? LoggerConfig.ROOT : getName();
119    }
120
121    @Override
122    public void start() {
123        LOGGER.trace("AsyncLoggerConfig[{}] starting...", displayName());
124        super.start();
125    }
126
127    @Override
128    public boolean stop(final long timeout, final TimeUnit timeUnit) {
129        setStopping();
130        super.stop(timeout, timeUnit, false);
131        LOGGER.trace("AsyncLoggerConfig[{}] stopping...", displayName());
132        setStopped();
133        return true;
134    }
135
136    /**
137     * Creates and returns a new {@code RingBufferAdmin} that instruments the
138     * ringbuffer of this {@code AsyncLoggerConfig}.
139     *
140     * @param contextName name of the {@code LoggerContext}
141     * @return a new {@code RingBufferAdmin} that instruments the ringbuffer
142     */
143    public RingBufferAdmin createRingBufferAdmin(final String contextName) {
144        return delegate.createRingBufferAdmin(contextName, getName());
145    }
146
147    /**
148     * Factory method to create a LoggerConfig.
149     *
150     * @param additivity True if additive, false otherwise.
151     * @param levelName The Level to be associated with the Logger.
152     * @param loggerName The name of the Logger.
153     * @param includeLocation "true" if location should be passed downstream
154     * @param refs An array of Appender names.
155     * @param properties Properties to pass to the Logger.
156     * @param config The Configuration.
157     * @param filter A Filter.
158     * @return A new LoggerConfig.
159     */
160    @PluginFactory
161    public static LoggerConfig createLogger(
162            @PluginAttribute("additivity") final String additivity,
163            @PluginAttribute("level") final String levelName,
164            @PluginAttribute("name") final String loggerName,
165            @PluginAttribute("includeLocation") final String includeLocation,
166            @PluginElement("AppenderRef") final AppenderRef[] refs,
167            @PluginElement("Properties") final Property[] properties,
168            @PluginConfiguration final Configuration config,
169            @PluginElement("Filter") final Filter filter) {
170        if (loggerName == null) {
171            LOGGER.error("Loggers cannot be configured without a name");
172            return null;
173        }
174
175        final List<AppenderRef> appenderRefs = Arrays.asList(refs);
176        Level level;
177        try {
178            level = Level.toLevel(levelName, Level.ERROR);
179        } catch (final Exception ex) {
180            LOGGER.error(
181                    "Invalid Log level specified: {}. Defaulting to Error",
182                    levelName);
183            level = Level.ERROR;
184        }
185        final String name = loggerName.equals(LoggerConfig.ROOT) ? Strings.EMPTY : loggerName;
186        final boolean additive = Booleans.parseBoolean(additivity, true);
187
188        return new AsyncLoggerConfig(name, appenderRefs, filter, level,
189                additive, properties, config, includeLocation(includeLocation));
190    }
191
192    // Note: for asynchronous loggers, includeLocation default is FALSE
193    protected static boolean includeLocation(final String includeLocationConfigValue) {
194        return Boolean.parseBoolean(includeLocationConfigValue);
195    }
196
197    /**
198     * An asynchronous root Logger.
199     */
200    @Plugin(name = "asyncRoot", category = "Core", printObject = true)
201    public static class RootLogger extends LoggerConfig {
202
203        @PluginFactory
204        public static LoggerConfig createLogger(
205                @PluginAttribute("additivity") final String additivity,
206                @PluginAttribute("level") final String levelName,
207                @PluginAttribute("includeLocation") final String includeLocation,
208                @PluginElement("AppenderRef") final AppenderRef[] refs,
209                @PluginElement("Properties") final Property[] properties,
210                @PluginConfiguration final Configuration config,
211                @PluginElement("Filter") final Filter filter) {
212            final List<AppenderRef> appenderRefs = Arrays.asList(refs);
213            Level level;
214            try {
215                level = Level.toLevel(levelName, Level.ERROR);
216            } catch (final Exception ex) {
217                LOGGER.error(
218                        "Invalid Log level specified: {}. Defaulting to Error",
219                        levelName);
220                level = Level.ERROR;
221            }
222            final boolean additive = Booleans.parseBoolean(additivity, true);
223
224            return new AsyncLoggerConfig(LogManager.ROOT_LOGGER_NAME,
225                    appenderRefs, filter, level, additive, properties, config,
226                    AsyncLoggerConfig.includeLocation(includeLocation));
227        }
228    }
229}