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          super();
51          AbstractLoggerAdapter adapter = null;
52          final String overrideAdaptorClassName =
53              PropertiesUtil.getProperties().getStringProperty(Constants.LOGGER_ADAPTOR_PROPERTY);
54          if (overrideAdaptorClassName != null) {
55              try {
56                  LOGGER.info("Trying to use LoggerAdaptor [{}] specified by Log4j property.", overrideAdaptorClassName);
57                  adapter = LoaderUtil.newCheckedInstanceOf(overrideAdaptorClassName, AbstractLoggerAdapter.class);
58              } catch (final Exception e) {
59                  LOGGER.error("Specified LoggerAdapter [{}] is incompatible.", overrideAdaptorClassName, e);
60              }
61          }
62          if (adapter == null) {
63              // default adapter
64              String adapterClassName;
65              try {
66                  // find out if log4j-core is available
67                  LoaderUtil.loadClass(Constants.CORE_LOGGER_CLASS_NAME);
68                  adapterClassName = Constants.CORE_LOGGER_ADAPTER_CLASS_NAME;
69              } catch (final ClassNotFoundException ignored) {
70                  adapterClassName = Constants.API_LOGGER_ADAPTER_CLASS_NAME;
71              }
72              LOGGER.debug("Attempting to use {}", adapterClassName);
73              try {
74                  adapter = LoaderUtil.newCheckedInstanceOf(adapterClassName, AbstractLoggerAdapter.class);
75              } catch (final Exception e) {
76                  throw LOGGER.throwing(new LoggingException(e));
77              }
78          }
79          loggerAdapter = adapter;
80          LOGGER.info("Registered Log4j as the java.util.logging.LogManager.");
81      }
82  
83      @Override
84      public boolean addLogger(final Logger logger) {
85          // in order to prevent non-bridged loggers from being registered, we always return false to indicate that
86          // the named logger should be obtained through getLogger(name)
87          return false;
88      }
89  
90      @Override
91      public Logger getLogger(final String name) {
92          LOGGER.trace("Call to LogManager.getLogger({})", name);
93          Set<String> activeRequests = recursive.get();
94          if (activeRequests.add(name)) {
95              try {
96                  return loggerAdapter.getLogger(name);
97              } finally {
98                  activeRequests.remove(name);
99              }
100         } else {
101             LOGGER.warn("Recursive call to getLogger for {} ignored.", name);
102             return new NoOpLogger(name);
103         }
104     }
105 
106     @Override
107     public Enumeration<String> getLoggerNames() {
108         return Collections.enumeration(loggerAdapter.getLoggersInContext(loggerAdapter.getContext()).keySet());
109     }
110 
111 }