001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.classic;
015
016import static ch.qos.logback.core.CoreConstants.EVALUATOR_MAP;
017
018import java.util.ArrayList;
019import java.util.Collection;
020import java.util.Collections;
021import java.util.HashMap;
022import java.util.List;
023import java.util.Map;
024import java.util.concurrent.ConcurrentHashMap;
025import java.util.concurrent.ScheduledFuture;
026
027import org.slf4j.ILoggerFactory;
028import org.slf4j.Marker;
029
030import ch.qos.logback.classic.spi.LoggerComparator;
031import ch.qos.logback.classic.spi.LoggerContextListener;
032import ch.qos.logback.classic.spi.LoggerContextVO;
033import ch.qos.logback.classic.spi.SequenceNumberGenerator;
034import ch.qos.logback.classic.spi.TurboFilterList;
035import ch.qos.logback.classic.turbo.TurboFilter;
036import ch.qos.logback.classic.util.LoggerNameUtil;
037import ch.qos.logback.core.ContextBase;
038import ch.qos.logback.core.boolex.EventEvaluator;
039import ch.qos.logback.core.spi.FilterReply;
040import ch.qos.logback.core.spi.LifeCycle;
041import ch.qos.logback.core.status.StatusListener;
042import ch.qos.logback.core.status.StatusManager;
043import ch.qos.logback.core.status.WarnStatus;
044
045/**
046 * LoggerContext glues many of the logback-classic components together. In
047 * principle, every logback-classic component instance is attached either
048 * directly or indirectly to a LoggerContext instance. Just as importantly
049 * LoggerContext implements the {@link ILoggerFactory} acting as the
050 * manufacturing source of {@link Logger} instances.
051 *
052 * @author Ceki Gulcu
053 */
054public class LoggerContext extends ContextBase implements ILoggerFactory, LifeCycle {
055
056    /** Default setting of packaging data in stack traces */
057    public static final boolean DEFAULT_PACKAGING_DATA = false;
058
059    final Logger root;
060    private int size;
061    private int noAppenderWarning = 0;
062    final private List<LoggerContextListener> loggerContextListenerList = new ArrayList<LoggerContextListener>();
063
064    private Map<String, Logger> loggerCache;
065
066    private LoggerContextVO loggerContextRemoteView;
067    private final TurboFilterList turboFilterList = new TurboFilterList();
068    private boolean packagingDataEnabled = DEFAULT_PACKAGING_DATA;
069    SequenceNumberGenerator sequenceNumberGenerator = null; // by default there is no SequenceNumberGenerator
070    
071    private int maxCallerDataDepth = ClassicConstants.DEFAULT_MAX_CALLEDER_DATA_DEPTH;
072
073    int resetCount = 0;
074    private List<String> frameworkPackages;
075
076    public LoggerContext() {
077        super();
078        this.loggerCache = new ConcurrentHashMap<String, Logger>();
079
080        this.loggerContextRemoteView = new LoggerContextVO(this);
081        this.root = new Logger(Logger.ROOT_LOGGER_NAME, null, this);
082        this.root.setLevel(Level.DEBUG);
083        loggerCache.put(Logger.ROOT_LOGGER_NAME, root);
084        initEvaluatorMap();
085        size = 1;
086        this.frameworkPackages = new ArrayList<String>();
087    }
088
089    void initEvaluatorMap() {
090        putObject(EVALUATOR_MAP, new HashMap<String, EventEvaluator<?>>());
091    }
092
093    /**
094     * A new instance of LoggerContextRemoteView needs to be created each time the
095     * name or propertyMap (including keys or values) changes.
096     */
097    private void updateLoggerContextVO() {
098        loggerContextRemoteView = new LoggerContextVO(this);
099    }
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}