View Javadoc
1   /*
2    * Copyright 2001-2004 The Apache Software Foundation.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.apache.log4j;
18  
19  import org.apache.log4j.spi.LoggerFactory;
20  
21  import java.util.concurrent.ConcurrentHashMap;
22  import java.util.concurrent.ConcurrentMap;
23  
24  /**
25   * This class is a factory that creates and maintains org.apache.log4j.Loggers
26   * wrapping org.slf4j.Loggers.
27   *
28   * It keeps a hashtable of all created org.apache.log4j.Logger instances so that
29   * all newly created instances are not duplicates of existing loggers.
30   *
31   * @author Sébastien Pennec
32   */
33  class Log4jLoggerFactory {
34  
35      // String, Logger
36      private static final ConcurrentMap<String, Logger> log4jLoggers = new ConcurrentHashMap<>();
37  
38      public static Logger getLogger(String name) {
39          org.apache.log4j.Logger instance = log4jLoggers.get(name);
40          if (instance != null) {
41              return instance;
42          } else {
43              Logger newInstance = new Logger(name);
44              Logger oldInstance = log4jLoggers.putIfAbsent(name, newInstance);
45              return oldInstance == null ? newInstance : oldInstance;
46          }
47      }
48  
49      public static Logger getLogger(String name, LoggerFactory loggerFactory) {
50          org.apache.log4j.Logger instance = log4jLoggers.get(name);
51          if (instance != null) {
52              return instance;
53          } else {
54              Logger newInstance = loggerFactory.makeNewLoggerInstance(name);
55              Logger oldInstance = log4jLoggers.putIfAbsent(name, newInstance);
56              return oldInstance == null ? newInstance : oldInstance;
57          }
58      }
59  }