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.async;
18  
19  import java.util.Arrays;
20  import java.util.List;
21  
22  import org.apache.logging.log4j.Level;
23  import org.apache.logging.log4j.LogManager;
24  import org.apache.logging.log4j.Logger;
25  import org.apache.logging.log4j.core.Filter;
26  import org.apache.logging.log4j.core.LogEvent;
27  import org.apache.logging.log4j.core.config.AppenderRef;
28  import org.apache.logging.log4j.core.config.Configuration;
29  import org.apache.logging.log4j.core.config.LoggerConfig;
30  import org.apache.logging.log4j.core.config.Property;
31  import org.apache.logging.log4j.core.config.plugins.Plugin;
32  import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
33  import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
34  import org.apache.logging.log4j.core.config.plugins.PluginElement;
35  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
36  import org.apache.logging.log4j.core.helpers.Booleans;
37  import org.apache.logging.log4j.status.StatusLogger;
38  
39  /**
40   * Asynchronous Logger object that is created via configuration and can be
41   * combined with synchronous loggers.
42   * <p>
43   * AsyncLoggerConfig is a logger designed for high throughput and low latency
44   * logging. It does not perform any I/O in the calling (application) thread, but
45   * instead hands off the work to another thread as soon as possible. The actual
46   * logging is performed in the background thread. It uses the LMAX Disruptor
47   * library for inter-thread communication. (<a
48   * href="http://lmax-exchange.github.com/disruptor/"
49   * >http://lmax-exchange.github.com/disruptor/</a>)
50   * <p>
51   * To use AsyncLoggerConfig, specify {@code <asyncLogger>} or
52   * {@code <asyncRoot>} in configuration.
53   * <p>
54   * Note that for performance reasons, this logger does not include source
55   * location by default. You need to specify {@code includeLocation="true"} in
56   * the configuration or any %class, %location or %line conversion patterns in
57   * your log4j.xml configuration will produce either a "?" character or no output
58   * at all.
59   * <p>
60   * For best performance, use AsyncLoggerConfig with the RandomAccessFileAppender or
61   * RollingRandomAccessFileAppender, with immediateFlush=false. These appenders have
62   * built-in support for the batching mechanism used by the Disruptor library,
63   * and they will flush to disk at the end of each batch. This means that even
64   * with immediateFlush=false, there will never be any items left in the buffer;
65   * all log events will all be written to disk in a very efficient manner.
66   */
67  @Plugin(name = "asyncLogger", category = "Core", printObject = true)
68  public class AsyncLoggerConfig extends LoggerConfig {
69  
70      private AsyncLoggerConfigHelper helper;
71  
72      /**
73       * Default constructor.
74       */
75      public AsyncLoggerConfig() {
76          super();
77      }
78  
79      /**
80       * Constructor that sets the name, level and additive values.
81       *
82       * @param name The Logger name.
83       * @param level The Level.
84       * @param additive true if the Logger is additive, false otherwise.
85       */
86      public AsyncLoggerConfig(final String name, final Level level,
87              final boolean additive) {
88          super(name, level, additive);
89      }
90  
91      protected AsyncLoggerConfig(final String name,
92              final List<AppenderRef> appenders, final Filter filter,
93              final Level level, final boolean additive,
94              final Property[] properties, final Configuration config,
95              final boolean includeLocation) {
96          super(name, appenders, filter, level, additive, properties, config,
97                  includeLocation);
98      }
99  
100     /**
101      * Passes on the event to a separate thread that will call
102      * {@link #asyncCallAppenders(LogEvent)}.
103      */
104     @Override
105     protected void callAppenders(final LogEvent event) {
106         // populate lazily initialized fields
107         event.getSource();
108         event.getThreadName();
109 
110         // pass on the event to a separate thread
111         helper.callAppendersFromAnotherThread(event);
112     }
113 
114     /** Called by AsyncLoggerConfigHelper.RingBufferLog4jEventHandler. */
115     void asyncCallAppenders(final LogEvent event) {
116         super.callAppenders(event);
117     }
118 
119     @Override
120     public void startFilter() {
121         if (helper == null) {
122             helper = new AsyncLoggerConfigHelper(this);
123         } else {
124             AsyncLoggerConfigHelper.claim(); // LOG4J2-336
125         }
126         super.startFilter();
127     }
128 
129     @Override
130     public void stopFilter() {
131         AsyncLoggerConfigHelper.release();
132         super.stopFilter();
133     }
134 
135     /**
136      * Factory method to create a LoggerConfig.
137      *
138      * @param additivity True if additive, false otherwise.
139      * @param levelName The Level to be associated with the Logger.
140      * @param loggerName The name of the Logger.
141      * @param includeLocation "true" if location should be passed downstream
142      * @param refs An array of Appender names.
143      * @param properties Properties to pass to the Logger.
144      * @param config The Configuration.
145      * @param filter A Filter.
146      * @return A new LoggerConfig.
147      */
148     @PluginFactory
149     public static LoggerConfig createLogger(
150             @PluginAttribute("additivity") final String additivity,
151             @PluginAttribute("level") final String levelName,
152             @PluginAttribute("name") final String loggerName,
153             @PluginAttribute("includeLocation") final String includeLocation,
154             @PluginElement("AppenderRef") final AppenderRef[] refs,
155             @PluginElement("Properties") final Property[] properties,
156             @PluginConfiguration final Configuration config,
157             @PluginElement("Filters") final Filter filter) {
158         if (loggerName == null) {
159             LOGGER.error("Loggers cannot be configured without a name");
160             return null;
161         }
162 
163         final List<AppenderRef> appenderRefs = Arrays.asList(refs);
164         Level level;
165         try {
166             level = Level.toLevel(levelName, Level.ERROR);
167         } catch (final Exception ex) {
168             LOGGER.error(
169                     "Invalid Log level specified: {}. Defaulting to Error",
170                     levelName);
171             level = Level.ERROR;
172         }
173         final String name = loggerName.equals("root") ? "" : loggerName;
174         final boolean additive = Booleans.parseBoolean(additivity, true);
175 
176         return new AsyncLoggerConfig(name, appenderRefs, filter, level,
177                 additive, properties, config, includeLocation(includeLocation));
178     }
179 
180     // Note: for asynchronous loggers, includeLocation default is FALSE
181     protected static boolean includeLocation(final String includeLocationConfigValue) {
182         return Boolean.parseBoolean(includeLocationConfigValue);
183     }
184 
185     /**
186      * An asynchronous root Logger.
187      */
188     @Plugin(name = "asyncRoot", category = "Core", printObject = true)
189     public static class RootLogger extends LoggerConfig {
190 
191         @PluginFactory
192         public static LoggerConfig createLogger(
193                 @PluginAttribute("additivity") final String additivity,
194                 @PluginAttribute("level") final String levelName,
195                 @PluginAttribute("includeLocation") final String includeLocation,
196                 @PluginElement("AppenderRef") final AppenderRef[] refs,
197                 @PluginElement("Properties") final Property[] properties,
198                 @PluginConfiguration final Configuration config,
199                 @PluginElement("Filters") final Filter filter) {
200             final List<AppenderRef> appenderRefs = Arrays.asList(refs);
201             Level level;
202             try {
203                 level = Level.toLevel(levelName, Level.ERROR);
204             } catch (final Exception ex) {
205                 LOGGER.error(
206                         "Invalid Log level specified: {}. Defaulting to Error",
207                         levelName);
208                 level = Level.ERROR;
209             }
210             final boolean additive = Booleans.parseBoolean(additivity, true);
211 
212             return new AsyncLoggerConfig(LogManager.ROOT_LOGGER_NAME,
213                     appenderRefs, filter, level, additive, properties, config,
214                     includeLocation(includeLocation));
215         }
216     }
217 }