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.spi;
18  
19  import java.util.HashSet;
20  import java.util.Map;
21  import java.util.Set;
22  import java.util.WeakHashMap;
23  import java.util.concurrent.ConcurrentHashMap;
24  import java.util.concurrent.ConcurrentMap;
25  import java.util.concurrent.locks.ReadWriteLock;
26  import java.util.concurrent.locks.ReentrantReadWriteLock;
27  
28  import org.apache.logging.log4j.LogManager;
29  import org.apache.logging.log4j.util.LoaderUtil;
30  
31  /**
32   * Provides an abstract base class to use for implementing LoggerAdapter.
33   * 
34   * @param <L> the Logger class to adapt
35   * @since 2.1
36   */
37  public abstract class AbstractLoggerAdapter<L> implements LoggerAdapter<L>, LoggerContextShutdownAware {
38  
39      /**
40       * A map to store loggers for their given LoggerContexts.
41       */
42      protected final Map<LoggerContext, ConcurrentMap<String, L>> registry = new ConcurrentHashMap<>();
43  
44      private final ReadWriteLock lock = new ReentrantReadWriteLock (true);
45  
46      @Override
47      public L getLogger(final String name) {
48          final LoggerContext context = getContext();
49          final ConcurrentMap<String, L> loggers = getLoggersInContext(context);
50          final L logger = loggers.get(name);
51          if (logger != null) {
52              return logger;
53          }
54          loggers.putIfAbsent(name, newLogger(name, context));
55          return loggers.get(name);
56      }
57  
58      @Override
59      public void contextShutdown(LoggerContext loggerContext) {
60          registry.remove(loggerContext);
61      }
62  
63      /**
64       * Gets or creates the ConcurrentMap of named loggers for a given LoggerContext.
65       *
66       * @param context the LoggerContext to get loggers for
67       * @return the map of loggers for the given LoggerContext
68       */
69      public ConcurrentMap<String, L> getLoggersInContext(final LoggerContext context) {
70          ConcurrentMap<String, L> loggers;
71          lock.readLock ().lock ();
72          try {
73              loggers = registry.get (context);
74          } finally {
75              lock.readLock ().unlock ();
76          }
77  
78          if (loggers != null) {
79              return loggers;
80          }
81          lock.writeLock ().lock ();
82          try {
83              loggers = registry.get (context);
84              if (loggers == null) {
85                  loggers = new ConcurrentHashMap<> ();
86                  registry.put (context, loggers);
87                  if (context instanceof LoggerContextShutdownEnabled) {
88                      ((LoggerContextShutdownEnabled) context).addShutdownListener(this);
89                  }
90              }
91              return loggers;
92          } finally {
93              lock.writeLock ().unlock ();
94          }
95      }
96  
97      /**
98       * For unit testing. Consider to be private.
99       */
100     public Set<LoggerContext> getLoggerContexts() {
101         return new HashSet<>(registry.keySet());
102     }
103 
104     /**
105      * Creates a new named logger for a given {@link LoggerContext}.
106      *
107      * @param name the name of the logger to create
108      * @param context the LoggerContext this logger will be associated with
109      * @return the new named logger
110      */
111     protected abstract L newLogger(final String name, final LoggerContext context);
112 
113     /**
114      * Gets the {@link LoggerContext} that should be used to look up or create loggers. This is similar in spirit to the
115      * {@code ContextSelector} class in {@code log4j-core}. However, implementations can rely on their own framework's
116      * separation of contexts instead (or simply use a singleton).
117      *
118      * @return the LoggerContext to be used for lookup and creation purposes
119      * @see org.apache.logging.log4j.LogManager#getContext(ClassLoader, boolean)
120      * @see org.apache.logging.log4j.LogManager#getContext(String, boolean)
121      */
122     protected abstract LoggerContext getContext();
123 
124     /**
125      * Gets the {@link LoggerContext} associated with the given caller class.
126      *
127      * @param callerClass the caller class
128      * @return the LoggerContext for the calling class
129      */
130     protected LoggerContext getContext(final Class<?> callerClass) {
131         ClassLoader cl = null;
132         if (callerClass != null) {
133             cl = callerClass.getClassLoader();
134         }
135         if (cl == null) {
136             cl = LoaderUtil.getThreadContextClassLoader();
137         }
138         return LogManager.getContext(cl, false);
139     }
140 
141     @Override
142     public void close() {
143         lock.writeLock ().lock ();
144         try {
145             registry.clear();
146         } finally {
147             lock.writeLock ().unlock ();
148         }
149     }
150 }