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.jul;
18  
19  import java.util.Collections;
20  import java.util.Enumeration;
21  import java.util.HashSet;
22  import java.util.Set;
23  import java.util.logging.Logger;
24  
25  import org.apache.logging.log4j.LoggingException;
26  import org.apache.logging.log4j.status.StatusLogger;
27  import org.apache.logging.log4j.util.LoaderUtil;
28  import org.apache.logging.log4j.util.PropertiesUtil;
29  
30  /**
31   * Log4j implementation of {@link java.util.logging.LogManager}. Note that the system property
32   * {@code java.util.logging.manager} must be set to {@code org.apache.logging.log4j.jul.LogManager} in order to use
33   * this adaptor. This LogManager requires the {@code log4j-api} library to be available. If {@code log4j-core} is
34   * also available, then more features of {@link java.util.logging.Logger} are supported.
35   *
36   * <p>To override the default {@link AbstractLoggerAdapter} that is used, specify the Log4j property
37   * {@code log4j.jul.LoggerAdapter} and set it to the fully qualified class name of a custom
38   * implementation. All implementations must have a default constructor.</p>
39   *
40   * @since 2.1
41   */
42  public class LogManager extends java.util.logging.LogManager {
43  
44      private static final org.apache.logging.log4j.Logger LOGGER = StatusLogger.getLogger();
45      private final AbstractLoggerAdapter loggerAdapter;
46      // Contains the set of logger names that are actively being requested using getLogger.
47      private final ThreadLocal<Set<String>> recursive = ThreadLocal.withInitial(HashSet::new);
48  
49      public LogManager() {
50          AbstractLoggerAdapter adapter = null;
51          final String overrideAdaptorClassName =
52              PropertiesUtil.getProperties().getStringProperty(Constants.LOGGER_ADAPTOR_PROPERTY);
53          if (overrideAdaptorClassName != null) {
54              try {
55                  LOGGER.info("Trying to use LoggerAdaptor [{}] specified by Log4j property.", overrideAdaptorClassName);
56                  adapter = LoaderUtil.newCheckedInstanceOf(overrideAdaptorClassName, AbstractLoggerAdapter.class);
57              } catch (final Exception e) {
58                  LOGGER.error("Specified LoggerAdapter [{}] is incompatible.", overrideAdaptorClassName, e);
59              }
60          }
61          if (adapter == null) {
62              // default adapter
63              String adapterClassName;
64              try {
65                  // find out if log4j-core is available
66                  LoaderUtil.loadClass(Constants.CORE_LOGGER_CLASS_NAME);
67                  adapterClassName = Constants.CORE_LOGGER_ADAPTER_CLASS_NAME;
68              } catch (final ClassNotFoundException ignored) {
69                  adapterClassName = Constants.API_LOGGER_ADAPTER_CLASS_NAME;
70              }
71              LOGGER.debug("Attempting to use {}", adapterClassName);
72              try {
73                  adapter = LoaderUtil.newCheckedInstanceOf(adapterClassName, AbstractLoggerAdapter.class);
74              } catch (final Exception e) {
75                  throw LOGGER.throwing(new LoggingException(e));
76              }
77          }
78          loggerAdapter = adapter;
79          LOGGER.info("Registered Log4j as the java.util.logging.LogManager.");
80      }
81  
82      @Override
83      public boolean addLogger(final Logger logger) {
84          // in order to prevent non-bridged loggers from being registered, we always return false to indicate that
85          // the named logger should be obtained through getLogger(name)
86          return false;
87      }
88  
89      @Override
90      public Logger getLogger(final String name) {
91          LOGGER.trace("Call to LogManager.getLogger({})", name);
92          Set<String> activeRequests = recursive.get();
93          if (activeRequests.add(name)) {
94              try {
95                  return loggerAdapter.getLogger(name);
96              } finally {
97                  activeRequests.remove(name);
98              }
99          }
100         LOGGER.warn("Recursive call to getLogger for {} ignored.", name);
101         return new NoOpLogger(name);
102     }
103 
104     @Override
105     public Enumeration<String> getLoggerNames() {
106         return Collections.enumeration(loggerAdapter.getLoggersInContext(loggerAdapter.getContext()).keySet());
107     }
108 
109 }