View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.classic;
15  
16  import static ch.qos.logback.core.CoreConstants.EVALUATOR_MAP;
17  
18  import java.util.ArrayList;
19  import java.util.Collection;
20  import java.util.Collections;
21  import java.util.HashMap;
22  import java.util.List;
23  import java.util.Map;
24  import java.util.concurrent.ConcurrentHashMap;
25  import java.util.concurrent.ScheduledFuture;
26  
27  import org.slf4j.ILoggerFactory;
28  import org.slf4j.Marker;
29  
30  import ch.qos.logback.classic.spi.LoggerComparator;
31  import ch.qos.logback.classic.spi.LoggerContextListener;
32  import ch.qos.logback.classic.spi.LoggerContextVO;
33  import ch.qos.logback.classic.spi.SequenceNumberGenerator;
34  import ch.qos.logback.classic.spi.TurboFilterList;
35  import ch.qos.logback.classic.turbo.TurboFilter;
36  import ch.qos.logback.classic.util.LoggerNameUtil;
37  import ch.qos.logback.core.ContextBase;
38  import ch.qos.logback.core.boolex.EventEvaluator;
39  import ch.qos.logback.core.spi.FilterReply;
40  import ch.qos.logback.core.spi.LifeCycle;
41  import ch.qos.logback.core.status.StatusListener;
42  import ch.qos.logback.core.status.StatusManager;
43  import ch.qos.logback.core.status.WarnStatus;
44  
45  /**
46   * LoggerContext glues many of the logback-classic components together. In
47   * principle, every logback-classic component instance is attached either
48   * directly or indirectly to a LoggerContext instance. Just as importantly
49   * LoggerContext implements the {@link ILoggerFactory} acting as the
50   * manufacturing source of {@link Logger} instances.
51   *
52   * @author Ceki Gulcu
53   */
54  public class LoggerContext extends ContextBase implements ILoggerFactory, LifeCycle {
55  
56      /** Default setting of packaging data in stack traces */
57      public static final boolean DEFAULT_PACKAGING_DATA = false;
58  
59      final Logger root;
60      private int size;
61      private int noAppenderWarning = 0;
62      final private List<LoggerContextListener> loggerContextListenerList = new ArrayList<LoggerContextListener>();
63  
64      private Map<String, Logger> loggerCache;
65  
66      private LoggerContextVO loggerContextRemoteView;
67      private final TurboFilterList turboFilterList = new TurboFilterList();
68      private boolean packagingDataEnabled = DEFAULT_PACKAGING_DATA;
69      SequenceNumberGenerator sequenceNumberGenerator = null; // by default there is no SequenceNumberGenerator
70      
71      private int maxCallerDataDepth = ClassicConstants.DEFAULT_MAX_CALLEDER_DATA_DEPTH;
72  
73      int resetCount = 0;
74      private List<String> frameworkPackages;
75  
76      public LoggerContext() {
77          super();
78          this.loggerCache = new ConcurrentHashMap<String, Logger>();
79  
80          this.loggerContextRemoteView = new LoggerContextVO(this);
81          this.root = new Logger(Logger.ROOT_LOGGER_NAME, null, this);
82          this.root.setLevel(Level.DEBUG);
83          loggerCache.put(Logger.ROOT_LOGGER_NAME, root);
84          initEvaluatorMap();
85          size = 1;
86          this.frameworkPackages = new ArrayList<String>();
87      }
88  
89      void initEvaluatorMap() {
90          putObject(EVALUATOR_MAP, new HashMap<String, EventEvaluator<?>>());
91      }
92  
93      /**
94       * A new instance of LoggerContextRemoteView needs to be created each time the
95       * name or propertyMap (including keys or values) changes.
96       */
97      private void updateLoggerContextVO() {
98          loggerContextRemoteView = new LoggerContextVO(this);
99      }
100 
101     @Override
102     public void putProperty(String key, String val) {
103         super.putProperty(key, val);
104         updateLoggerContextVO();
105     }
106 
107     @Override
108     public void setName(String name) {
109         super.setName(name);
110         updateLoggerContextVO();
111     }
112 
113     public final Logger getLogger(final Class<?> clazz) {
114         return getLogger(clazz.getName());
115     }
116 
117     @Override
118     public Logger getLogger(final String name) {
119 
120         if (name == null) {
121             throw new IllegalArgumentException("name argument cannot be null");
122         }
123 
124         // if we are asking for the root logger, then let us return it without
125         // wasting time
126         if (Logger.ROOT_LOGGER_NAME.equalsIgnoreCase(name)) {
127             return root;
128         }
129 
130         int i = 0;
131         Logger logger = root;
132 
133         // check if the desired logger exists, if it does, return it
134         // without further ado.
135         Logger childLogger = (Logger) loggerCache.get(name);
136         // if we have the child, then let us return it without wasting time
137         if (childLogger != null) {
138             return childLogger;
139         }
140 
141         // if the desired logger does not exist, them create all the loggers
142         // in between as well (if they don't already exist)
143         String childName;
144         while (true) {
145             int h = LoggerNameUtil.getSeparatorIndexOf(name, i);
146             if (h == -1) {
147                 childName = name;
148             } else {
149                 childName = name.substring(0, h);
150             }
151             // move i left of the last point
152             i = h + 1;
153             synchronized (logger) {
154                 childLogger = logger.getChildByName(childName);
155                 if (childLogger == null) {
156                     childLogger = logger.createChildByName(childName);
157                     loggerCache.put(childName, childLogger);
158                     incSize();
159                 }
160             }
161             logger = childLogger;
162             if (h == -1) {
163                 return childLogger;
164             }
165         }
166     }
167 
168     private void incSize() {
169         size++;
170     }
171 
172     int size() {
173         return size;
174     }
175 
176     /**
177      * Check if the named logger exists in the hierarchy. If so return its
178      * reference, otherwise returns <code>null</code>.
179      *
180      * @param name the name of the logger to search for.
181      */
182     public Logger exists(String name) {
183         return (Logger) loggerCache.get(name);
184     }
185 
186     final void noAppenderDefinedWarning(final Logger logger) {
187         if (noAppenderWarning++ == 0) {
188             getStatusManager().add(new WarnStatus("No appenders present in context [" + getName() + "] for logger [" + logger.getName() + "].", logger));
189         }
190     }
191 
192     public List<Logger> getLoggerList() {
193         Collection<Logger> collection = loggerCache.values();
194         List<Logger> loggerList = new ArrayList<Logger>(collection);
195         Collections.sort(loggerList, new LoggerComparator());
196         return loggerList;
197     }
198 
199     public LoggerContextVO getLoggerContextRemoteView() {
200         return loggerContextRemoteView;
201     }
202 
203     public void setPackagingDataEnabled(boolean packagingDataEnabled) {
204         this.packagingDataEnabled = packagingDataEnabled;
205     }
206 
207     public boolean isPackagingDataEnabled() {
208         return packagingDataEnabled;
209     }
210 
211     /**
212      * This method clears all internal properties, except internal status messages,
213      * closes all appenders, removes any turboFilters, fires an OnReset event,
214      * removes all status listeners, removes all context listeners
215      * (except those which are reset resistant).
216      * <p/>
217      * As mentioned above, internal status messages survive resets.
218      */
219     @Override
220     public void reset() {
221         resetCount++;
222         super.reset();
223         initEvaluatorMap();
224         initCollisionMaps();
225         root.recursiveReset();
226         resetTurboFilterList();
227         cancelScheduledTasks();
228         fireOnReset();
229         resetListenersExceptResetResistant();
230         resetStatusListeners();
231     }
232 
233     private void cancelScheduledTasks() {
234         for(ScheduledFuture<?> sf: scheduledFutures) {
235             sf.cancel(false);
236         }
237         scheduledFutures.clear();
238     }
239 
240     private void resetStatusListeners() {
241         StatusManager sm = getStatusManager();
242         for (StatusListener sl : sm.getCopyOfStatusListenerList()) {
243             sm.remove(sl);
244         }
245     }
246 
247     public TurboFilterList getTurboFilterList() {
248         return turboFilterList;
249     }
250 
251     public void addTurboFilter(TurboFilter newFilter) {
252         turboFilterList.add(newFilter);
253     }
254 
255     /**
256      * First processPriorToRemoval all registered turbo filters and then clear the registration
257      * list.
258      */
259     public void resetTurboFilterList() {
260         for (TurboFilter tf : turboFilterList) {
261             tf.stop();
262         }
263         turboFilterList.clear();
264     }
265 
266     final FilterReply getTurboFilterChainDecision_0_3OrMore(final Marker marker, final Logger logger, final Level level, final String format,
267                     final Object[] params, final Throwable t) {
268         if (turboFilterList.size() == 0) {
269             return FilterReply.NEUTRAL;
270         }
271         return turboFilterList.getTurboFilterChainDecision(marker, logger, level, format, params, t);
272     }
273 
274     final FilterReply getTurboFilterChainDecision_1(final Marker marker, final Logger logger, final Level level, final String format, final Object param,
275                     final Throwable t) {
276         if (turboFilterList.size() == 0) {
277             return FilterReply.NEUTRAL;
278         }
279         return turboFilterList.getTurboFilterChainDecision(marker, logger, level, format, new Object[] { param }, t);
280     }
281 
282     final FilterReply getTurboFilterChainDecision_2(final Marker marker, final Logger logger, final Level level, final String format, final Object param1,
283                     final Object param2, final Throwable t) {
284         if (turboFilterList.size() == 0) {
285             return FilterReply.NEUTRAL;
286         }
287         return turboFilterList.getTurboFilterChainDecision(marker, logger, level, format, new Object[] { param1, param2 }, t);
288     }
289 
290     // === start listeners ==============================================
291     public void addListener(LoggerContextListener listener) {
292         loggerContextListenerList.add(listener);
293     }
294 
295     public void removeListener(LoggerContextListener listener) {
296         loggerContextListenerList.remove(listener);
297     }
298 
299     private void resetListenersExceptResetResistant() {
300         List<LoggerContextListener> toRetain = new ArrayList<LoggerContextListener>();
301 
302         for (LoggerContextListener lcl : loggerContextListenerList) {
303             if (lcl.isResetResistant()) {
304                 toRetain.add(lcl);
305             }
306         }
307         loggerContextListenerList.retainAll(toRetain);
308     }
309 
310     private void resetAllListeners() {
311         loggerContextListenerList.clear();
312     }
313 
314     public List<LoggerContextListener> getCopyOfListenerList() {
315         return new ArrayList<LoggerContextListener>(loggerContextListenerList);
316     }
317 
318     void fireOnLevelChange(Logger logger, Level level) {
319         for (LoggerContextListener listener : loggerContextListenerList) {
320             listener.onLevelChange(logger, level);
321         }
322     }
323 
324     private void fireOnReset() {
325         for (LoggerContextListener listener : loggerContextListenerList) {
326             listener.onReset(this);
327         }
328     }
329 
330     private void fireOnStart() {
331         for (LoggerContextListener listener : loggerContextListenerList) {
332             listener.onStart(this);
333         }
334     }
335 
336     private void fireOnStop() {
337         for (LoggerContextListener listener : loggerContextListenerList) {
338             listener.onStop(this);
339         }
340     }
341 
342     // === end listeners ==============================================
343 
344     public void start() {
345         super.start();
346         fireOnStart();
347     }
348 
349     public void stop() {
350         reset();
351         fireOnStop();
352         resetAllListeners();
353         super.stop();
354     }
355 
356     @Override
357     public String toString() {
358         return this.getClass().getName() + "[" + getName() + "]";
359     }
360 
361     public int getMaxCallerDataDepth() {
362         return maxCallerDataDepth;
363     }
364 
365     public void setMaxCallerDataDepth(int maxCallerDataDepth) {
366         this.maxCallerDataDepth = maxCallerDataDepth;
367     }
368 
369     /**
370      * List of packages considered part of the logging framework such that they are never considered
371      * as callers of the logging framework. This list used to compute the caller for logging events.
372      * <p/>
373      * To designate package "com.foo" as well as all its subpackages as being part of the logging framework, simply add
374      * "com.foo" to this list.
375      *
376      * @return list of framework packages
377      */
378     public List<String> getFrameworkPackages() {
379         return frameworkPackages;
380     }
381 
382     public SequenceNumberGenerator getSequenceNumberGenerator() {
383         return null;
384     }
385 }