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.config;
18  
19  import org.apache.logging.log4j.Level;
20  import org.apache.logging.log4j.LogManager;
21  import org.apache.logging.log4j.Logger;
22  import org.apache.logging.log4j.core.LoggerContext;
23  import org.apache.logging.log4j.core.impl.Log4jContextFactory;
24  import org.apache.logging.log4j.core.util.NetUtils;
25  import org.apache.logging.log4j.spi.LoggerContextFactory;
26  import org.apache.logging.log4j.status.StatusLogger;
27  import org.apache.logging.log4j.util.Strings;
28  
29  import java.net.URI;
30  import java.util.ArrayList;
31  import java.util.List;
32  import java.util.Map;
33  import java.util.concurrent.TimeUnit;
34  
35  /**
36   * Initializes and configure the Logging system. This class provides several ways to construct a LoggerContext using
37   * the location of a configuration file, a context name, and various optional parameters.
38   */
39  public final class Configurator {
40  
41      private static final String FQCN = Configurator.class.getName();
42  
43      private static final Logger LOGGER = StatusLogger.getLogger();
44  
45      private static Log4jContextFactory getFactory() {
46          final LoggerContextFactory factory = LogManager.getFactory();
47          if (factory instanceof Log4jContextFactory) {
48              return (Log4jContextFactory) factory;
49          } else if (factory != null) {
50              LOGGER.error("LogManager returned an instance of {} which does not implement {}. Unable to initialize Log4j.",
51                      factory.getClass().getName(), Log4jContextFactory.class.getName());
52              return null;
53          } else {
54              LOGGER.fatal("LogManager did not return a LoggerContextFactory. This indicates something has gone terribly wrong!");
55              return null;
56          }
57      }
58  
59      /**
60       * Initializes the Logging Context.
61       * @param loader The ClassLoader for the Context (or null).
62       * @param source The InputSource for the configuration.
63       * @return The LoggerContext.
64       */
65      public static LoggerContext initialize(final ClassLoader loader,
66                                             final ConfigurationSource source) {
67          return initialize(loader, source, null);
68      }
69  
70      /**
71       * Initializes the Logging Context.
72       * @param loader The ClassLoader for the Context (or null).
73       * @param source The InputSource for the configuration.
74       * @param externalContext The external context to be attached to the LoggerContext.
75       * @return The LoggerContext.
76       */
77  
78      public static LoggerContext initialize(final ClassLoader loader,
79                                             final ConfigurationSource source,
80                                             final Object externalContext)
81      {
82  
83          try {
84              final Log4jContextFactory factory = getFactory();
85              return factory == null ? null :
86                      factory.getContext(FQCN, loader, externalContext, false, source);
87          } catch (final Exception ex) {
88              LOGGER.error("There was a problem obtaining a LoggerContext using the configuration source [{}]", source, ex);
89          }
90          return null;
91      }
92  
93      /**
94       * Initializes the Logging Context.
95       * @param name The Context name.
96       * @param loader The ClassLoader for the Context (or null).
97       * @param configLocation The configuration for the logging context.
98       * @return The LoggerContext or null if an error occurred (check the status logger).
99       */
100     public static LoggerContext initialize(final String name, final ClassLoader loader, final String configLocation) {
101         return initialize(name, loader, configLocation, null);
102 
103     }
104 
105     /**
106      * Initializes the Logging Context.
107      * @param name The Context name.
108      * @param loader The ClassLoader for the Context (or null).
109      * @param configLocation The configuration for the logging context (or null, or blank).
110      * @param externalContext The external context to be attached to the LoggerContext
111      * @return The LoggerContext or null if an error occurred (check the status logger).
112      */
113     public static LoggerContext initialize(final String name, final ClassLoader loader, final String configLocation,
114             final Object externalContext) {
115         if (Strings.isBlank(configLocation)) {
116             return initialize(name, loader, (URI) null, externalContext);
117         }
118         if (configLocation.contains(",")) {
119             final String[] parts = configLocation.split(",");
120             String scheme = null;
121             final List<URI> uris = new ArrayList<>(parts.length);
122             for (final String part : parts) {
123                 final URI uri = NetUtils.toURI(scheme != null ? scheme + ":" + part.trim() : part.trim());
124                 if (scheme == null && uri.getScheme() != null) {
125                     scheme = uri.getScheme();
126                 }
127                 uris.add(uri);
128             }
129             return initialize(name, loader, uris, externalContext);
130         }
131         return initialize(name, loader, NetUtils.toURI(configLocation), externalContext);
132     }
133 
134     /**
135      * Initializes the Logging Context.
136      * @param name The Context name.
137      * @param loader The ClassLoader for the Context (or null).
138      * @param configLocation The configuration for the logging context.
139      * @return The LoggerContext.
140      */
141     public static LoggerContext initialize(final String name, final ClassLoader loader, final URI configLocation) {
142         return initialize(name, loader, configLocation, null);
143     }
144 
145     /**
146      * Initializes the Logging Context.
147      * @param name The Context name.
148      * @param loader The ClassLoader for the Context (or null).
149      * @param configLocation The configuration for the logging context (or null).
150      * @param externalContext The external context to be attached to the LoggerContext
151      * @return The LoggerContext.
152      */
153     public static LoggerContext initialize(final String name, final ClassLoader loader, final URI configLocation,
154                                            final Object externalContext) {
155 
156         try {
157             final Log4jContextFactory factory = getFactory();
158             return factory == null ? null :
159                     factory.getContext(FQCN, loader, externalContext, false, configLocation, name);
160         } catch (final Exception ex) {
161             LOGGER.error("There was a problem initializing the LoggerContext [{}] using configuration at [{}].",
162                     name, configLocation, ex);
163         }
164         return null;
165     }
166 
167     public static LoggerContext initialize(final String name, final ClassLoader loader, final List<URI> configLocations,
168             final Object externalContext) {
169         try {
170             final Log4jContextFactory factory = getFactory();
171             return factory == null ?
172                     null :
173                     factory.getContext(FQCN, loader, externalContext, false, configLocations, name);
174         } catch (final Exception ex) {
175             LOGGER.error("There was a problem initializing the LoggerContext [{}] using configurations at [{}].", name,
176                     configLocations, ex);
177         }
178         return null;
179     }
180 
181     /**
182      * Initializes the Logging Context.
183      * @param name The Context name.
184      * @param configLocation The configuration for the logging context.
185      * @return The LoggerContext or null if an error occurred (check the status logger).
186      */
187     public static LoggerContext initialize(final String name, final String configLocation) {
188         return initialize(name, null, configLocation);
189     }
190 
191     /**
192      * Initializes the Logging Context.
193      * @param configuration The Configuration.
194      * @return The LoggerContext.
195      */
196     public static LoggerContext initialize(final Configuration configuration) {
197         return initialize(null, configuration, null);
198     }
199 
200     /**
201      * Initializes the Logging Context.
202      * @param loader The ClassLoader.
203      * @param configuration The Configuration.
204      * @return The LoggerContext.
205      */
206     public static LoggerContext initialize(final ClassLoader loader, final Configuration configuration) {
207         return initialize(loader, configuration, null);
208     }
209 
210     /**
211      * Initializes the Logging Context.
212      * @param loader The ClassLoader.
213      * @param configuration The Configuration.
214      * @param externalContext - The external context to be attached to the LoggerContext.
215      * @return The LoggerContext.
216      */
217     public static LoggerContext initialize(final ClassLoader loader, final Configuration configuration, final Object externalContext) {
218         try {
219             final Log4jContextFactory factory = getFactory();
220             return factory == null ? null :
221                     factory.getContext(FQCN, loader, externalContext, false, configuration);
222         } catch (final Exception ex) {
223             LOGGER.error("There was a problem initializing the LoggerContext using configuration {}",
224                     configuration.getName(), ex);
225         }
226         return null;
227     }
228 
229     /**
230      * Reconfigure using an already constructed Configuration.
231      * @param configuration The configuration.
232      * @since 2.13.0
233      */
234     public static void reconfigure(final Configuration configuration) {
235         try {
236             final Log4jContextFactory factory = getFactory();
237             if (factory != null) {
238                 factory.getContext(FQCN, null, null, false)
239                         .reconfigure(configuration);
240             }
241         } catch (final Exception ex) {
242             LOGGER.error("There was a problem initializing the LoggerContext using configuration {}",
243                     configuration.getName(), ex);
244         }
245     }
246 
247     /**
248      * Reload the existing reconfiguration.
249      * @since 2.12.0
250      */
251     public static void reconfigure() {
252         try {
253             Log4jContextFactory factory = getFactory();
254             if (factory != null) {
255                 factory.getSelector().getContext(FQCN, null, false).reconfigure();
256             } else {
257                 LOGGER.warn("Unable to reconfigure - Log4j has not been initialized.");
258             }
259         } catch (final Exception ex) {
260             LOGGER.error("Error encountered trying to reconfigure logging", ex);
261         }
262     }
263 
264     /**
265      * Reconfigure with a potentially new configuration.
266      * @param uri The location of the configuration.
267      * @since 2.12.0
268      */
269     public static void reconfigure(final URI uri) {
270         try {
271             Log4jContextFactory factory = getFactory();
272             if (factory != null) {
273                 factory.getSelector().getContext(FQCN, null, false).setConfigLocation(uri);
274             } else {
275                 LOGGER.warn("Unable to reconfigure - Log4j has not been initialized.");
276             }
277         } catch (final Exception ex) {
278             LOGGER.error("Error encountered trying to reconfigure logging", ex);
279         }
280     }
281 
282     /**
283      * Sets the levels of <code>parentLogger</code> and all 'child' loggers to the given <code>level</code>.
284      * @param parentLogger the parent logger
285      * @param level the new level
286      */
287     public static void setAllLevels(final String parentLogger, final Level level) {
288         // 1) get logger config
289         // 2) if exact match, use it, if not, create it.
290         // 3) set level on logger config
291         // 4) update child logger configs with level
292         // 5) update loggers
293         final LoggerContext loggerContext = LoggerContext.getContext(false);
294         final Configuration config = loggerContext.getConfiguration();
295         boolean set = setLevel(parentLogger, level, config);
296         for (final Map.Entry<String, LoggerConfig> entry : config.getLoggers().entrySet()) {
297             if (entry.getKey().startsWith(parentLogger)) {
298                 set |= setLevel(entry.getValue(), level);
299             }
300         }
301         if (set) {
302             loggerContext.updateLoggers();
303         }
304     }
305 
306     private static boolean setLevel(final LoggerConfig loggerConfig, final Level level) {
307         final boolean set = !loggerConfig.getLevel().equals(level);
308         if (set) {
309             loggerConfig.setLevel(level);
310         }
311         return set;
312     }
313 
314     /**
315      * Sets logger levels.
316      *
317      * @param levelMap
318      *            a levelMap where keys are level names and values are new
319      *            Levels.
320      */
321     public static void setLevel(final Map<String, Level> levelMap) {
322         final LoggerContext loggerContext = LoggerContext.getContext(false);
323         final Configuration config = loggerContext.getConfiguration();
324         boolean set = false;
325         for (final Map.Entry<String, Level> entry : levelMap.entrySet()) {
326             final String loggerName = entry.getKey();
327             final Level level = entry.getValue();
328             set |= setLevel(loggerName, level, config);
329         }
330         if (set) {
331             loggerContext.updateLoggers();
332         }
333     }
334 
335     /**
336      * Sets a logger's level.
337      *
338      * @param loggerName
339      *            the logger name
340      * @param level
341      *            the new level
342      */
343     public static void setLevel(final String loggerName, final Level level) {
344         final LoggerContext loggerContext = LoggerContext.getContext(false);
345         if (Strings.isEmpty(loggerName)) {
346             setRootLevel(level);
347         } else {
348             if (setLevel(loggerName, level, loggerContext.getConfiguration())) {
349                 loggerContext.updateLoggers();
350             }
351         }
352     }
353 
354     private static boolean setLevel(final String loggerName, final Level level, final Configuration config) {
355         boolean set;
356         LoggerConfig loggerConfig = config.getLoggerConfig(loggerName);
357         if (!loggerName.equals(loggerConfig.getName())) {
358             // TODO Should additivity be inherited?
359             loggerConfig = new LoggerConfig(loggerName, level, true);
360             config.addLogger(loggerName, loggerConfig);
361             loggerConfig.setLevel(level);
362             set = true;
363         } else {
364             set = setLevel(loggerConfig, level);
365         }
366         return set;
367     }
368 
369     /**
370      * Sets the root logger's level.
371      *
372      * @param level
373      *            the new level
374      */
375     public static void setRootLevel(final Level level) {
376         final LoggerContext loggerContext = LoggerContext.getContext(false);
377         final LoggerConfig loggerConfig = loggerContext.getConfiguration().getRootLogger();
378         if (!loggerConfig.getLevel().equals(level)) {
379             loggerConfig.setLevel(level);
380             loggerContext.updateLoggers();
381         }
382     }
383 
384     /**
385      * Shuts down the given logger context. This request does not wait for Log4j tasks to complete.
386      * <p>
387      * Log4j starts threads to perform certain actions like file rollovers; calling this method will not wait until the
388      * rollover thread is done. When this method returns, these tasks' status are undefined, the tasks may be done or
389      * not.
390      * </p>
391      *
392      * @param ctx
393      *            the logger context to shut down, may be null.
394      */
395     public static void shutdown(final LoggerContext ctx) {
396         if (ctx != null) {
397             ctx.stop();
398         }
399     }
400 
401     /**
402      * Shuts down the given logger context.
403      * <p>
404      * Log4j can start threads to perform certain actions like file rollovers; calling this method with a positive
405      * timeout will block until the rollover thread is done.
406      * </p>
407      *
408      * @param ctx
409      *            the logger context to shut down, may be null.
410      * @param timeout
411      *            the maximum time to wait
412      * @param timeUnit
413      *            the time unit of the timeout argument
414      * @return {@code true} if the logger context terminated and {@code false} if the timeout elapsed before
415      *         termination.
416      *
417      * @see LoggerContext#stop(long, TimeUnit)
418      *
419      * @since 2.7
420      */
421     public static boolean shutdown(final LoggerContext ctx, final long timeout, final TimeUnit timeUnit) {
422         if (ctx != null) {
423             return ctx.stop(timeout, timeUnit);
424         }
425         return true;
426     }
427 
428     private Configurator() {
429         // empty
430     }
431 }