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.core.util; 015 016import ch.qos.logback.core.Context; 017import ch.qos.logback.core.CoreConstants; 018import ch.qos.logback.core.spi.ContextAware; 019import ch.qos.logback.core.spi.LifeCycle; 020import ch.qos.logback.core.status.OnConsoleStatusListener; 021import ch.qos.logback.core.status.StatusListener; 022 023public class StatusListenerConfigHelper { 024 025 public static void installIfAsked(Context context) { 026 String slClass = OptionHelper.getSystemProperty(CoreConstants.STATUS_LISTENER_CLASS_KEY); 027 if (!OptionHelper.isNullOrEmpty(slClass)) { 028 addStatusListener(context, slClass); 029 } 030 } 031 032 private static void addStatusListener(Context context, String listenerClassName) { 033 StatusListener listener = null; 034 if (CoreConstants.SYSOUT.equalsIgnoreCase(listenerClassName)) { 035 listener = new OnConsoleStatusListener(); 036 } else { 037 listener = createListenerPerClassName(context, listenerClassName); 038 } 039 initAndAddListener(context, listener); 040 } 041 042 private static void initAndAddListener(Context context, StatusListener listener) { 043 if (listener != null) { 044 if (listener instanceof ContextAware) // LOGBACK-767 045 ((ContextAware) listener).setContext(context); 046 047 boolean effectivelyAdded = context.getStatusManager().add(listener); 048 if (effectivelyAdded && (listener instanceof LifeCycle)) { 049 ((LifeCycle) listener).start(); // LOGBACK-767 050 } 051 } 052 } 053 054 private static StatusListener createListenerPerClassName(Context context, String listenerClass) { 055 try { 056 return (StatusListener) OptionHelper.instantiateByClassName(listenerClass, StatusListener.class, context); 057 } catch (Exception e) { 058 // printing on the console is the best we can do 059 e.printStackTrace(); 060 return null; 061 } 062 } 063 064 /** 065 * This utility method adds a new OnConsoleStatusListener to the context passed 066 * as parameter. 067 * 068 * @param context 069 * @since 1.0.1 070 */ 071 static public void addOnConsoleListenerInstance(Context context, OnConsoleStatusListener onConsoleStatusListener) { 072 onConsoleStatusListener.setContext(context); 073 boolean effectivelyAdded = context.getStatusManager().add(onConsoleStatusListener); 074 if (effectivelyAdded) { 075 onConsoleStatusListener.start(); 076 } 077 } 078}