Example usage for java.util.logging Logger getParent

List of usage examples for java.util.logging Logger getParent

Introduction

In this page you can find the example usage for java.util.logging Logger getParent.

Prototype

public Logger getParent() 

Source Link

Document

Return the parent for this Logger.

Usage

From source file:Main.java

public static Level getLevel(Logger logger) {
    Level level = logger.getLevel();
    while (level == null && logger.getParent() != null) {
        logger = logger.getParent();/*from  w w  w  .  ja  va  2 s  .  c  om*/
        level = logger.getLevel();
    }
    return level;
}

From source file:alma.acs.logging.AcsLogger.java

/**
 * Client applications that use ACS class <code>ComponentClient</code> may need to turn their own JDK Logger into
 * an <code>AcsLogger</code>.
 * <p>//from w  ww. jav  a2  s.co m
 * If <code>logger</code> is itself of sub-type <code>AcsLogger</code> then it is returned directly without being wrapped.
 * The wrapping logger shares the parent logger and the log level with the provided logger.
 * 
 * @param logger
 *            the JDK logger
 * @param wrapperName
 *            Name of the returned AcsLogger. May be <code>null</code> in which case the delegate's name plus
 *            "wrapper" is taken.
 * @return an AcsLogger that delegates to the given <code>logger</code>.
 * @since ACS 8.0
 */
public static AcsLogger fromJdkLogger(Logger logger, String wrapLoggerName) {
    if (logger instanceof AcsLogger) {
        return (AcsLogger) logger;
    }
    String acsLoggerName = (wrapLoggerName != null ? wrapLoggerName.trim() : logger.getName() + "wrapper");
    AcsLogger ret = new AcsLogger(acsLoggerName, logger.getResourceBundleName(), null, true, logger);
    ret.setLevel(logger.getLevel());
    ret.setParent(logger.getParent());
    return ret;
}

From source file:org.osiam.addons.selfadministration.exception.OsiamExceptionHandler.java

private Level getLogLevel(Logger logger) {
    Level level = null;//from  w w  w.java 2  s  . co  m
    if (logger != null) {
        level = logger.getLevel();
    }
    if (level == null) {
        level = getLogLevel(logger.getParent());
    }
    return level;
}

From source file:com.twitter.common.net.http.handlers.LogConfig.java

private void maybeAdjustHandlerLevels(Logger logger, Level newLevel) {
    do {/*  w w  w  .j  av a 2s. c  o  m*/
        for (Handler handler : logger.getHandlers()) {
            Level handlerLevel = handler.getLevel();
            if (newLevel.intValue() < handlerLevel.intValue()) {
                handler.setLevel(newLevel);
            }
        }
    } while (logger.getUseParentHandlers() && (logger = logger.getParent()) != null);
}

From source file:org.callimachusproject.repository.CalliRepository.java

private void setHandlerLevel(Logger logger, Level level) {
    if (logger.getParent() != null) {
        setHandlerLevel(logger.getParent(), level);
    }/* w  w  w.  ja  v a2  s. c o m*/
    Handler[] handlers = logger.getHandlers();
    if (handlers != null) {
        for (Handler handler : handlers) {
            if (handler.getLevel().intValue() > level.intValue()) {
                handler.setLevel(level);
            }
        }
    }
}

From source file:alma.acs.logging.AcsLogger.java

/**
 * Logs the given <code>LogRecord</code>. 
 * The record can be modified or dropped by the optional filters provided in {@link #addLogRecordFilter(alma.acs.logging.AcsLogger.LogRecordFilter)}. 
 * <p>/*w ww  .  j av a 2s. c  o  m*/
 * Adding of context information:
 * <ul>
 * <li> If the LogRecord has a parameter that is a map which contains additional information 
 * about the line of code, thread, etc., the log record will be taken as provided, and no context
 * information will be added. This can be useful if
 *   <ul>
 *   <li> the log record was reconstructed from a remote error by the ACS error handling code
 *        (see <code>AcsJException</code>), or
 *   <li> if in very exceptional cases application code needs to manipulate such information by hand.
 *   </ul>
 * <li> otherwise, context information is inferred, similar to {@link LogRecord#inferCaller()},
 *   but additionally including thread name and line of code.
 * </ul>  
 * Note that by overloading this method, we intercept all logging activities of the base class.
 *  
 * @see java.util.logging.Logger#log(java.util.logging.LogRecord)
 */
public void log(LogRecord record) {
    // Throw exception if level OFF was used to log this record, see http://jira.alma.cl/browse/COMP-1928
    // Both Level.OFF and AcsLogLevel.OFF use the same value INTEGER.max, but we anyway check for both.
    if (record.getLevel().intValue() == Level.OFF.intValue()
            || record.getLevel().intValue() == AcsLogLevel.OFF.intValue()) {
        throw new IllegalArgumentException(
                "Level OFF must not be used for actual logging, but only for level filtering.");
    }

    StopWatch sw_all = null;
    if (PROFILE) {
        sw_all = new StopWatch(null);
    }

    // Level could be null and must then be inherited from the ancestor loggers, 
    // e.g. during JDK shutdown when the log level is nulled by the JDK LogManager 
    Logger loggerWithLevel = this;
    while (loggerWithLevel != null && loggerWithLevel.getLevel() == null
            && loggerWithLevel.getParent() != null) {
        loggerWithLevel = loggerWithLevel.getParent();
    }
    int levelValue = -1;
    if (loggerWithLevel.getLevel() == null) {
        // HSO 2007-09-05: With ACS 6.0.4 the OMC uses this class (previously plain JDK logger) and has reported 
        // that no level was found, which yielded a NPE. To be investigated further. 
        // Probably #createUnconfiguredLogger was used without setting parent logger nor log level. 
        // Just to be safe I add the necessary checks and warning message that improve over a NPE.
        if (!noLevelWarningPrinted) {
            System.out.println("Logger configuration error: no log level found for logger " + getLoggerName()
                    + " or its ancestors. Will use Level.ALL instead.");
            noLevelWarningPrinted = true;
        }
        // @TODO: decide if resorting to ALL is desirable, or to use schema defaults, INFO, etc
        levelValue = Level.ALL.intValue();
    } else {
        // level is fine, reset the flag to print the error message again when log level is missing.
        noLevelWarningPrinted = false;
        levelValue = loggerWithLevel.getLevel().intValue();
    }

    // filter by log level to avoid unnecessary retrieval of context data.
    // The same check will be repeated by the base class implementation of this method that gets called afterwards.
    if (record.getLevel().intValue() < levelValue || levelValue == offValue) {
        return;
    }

    // modify the logger name if necessary
    if (loggerName != null) {
        record.setLoggerName(loggerName);
    }

    // check if this record already has the context data attached which ACS needs but the JDK logging API does not provide
    LogParameterUtil paramUtil = new LogParameterUtil(record);
    Map<String, Object> specialProperties = paramUtil.extractSpecialPropertiesMap();

    if (specialProperties == null) {
        // we prepend the special properties map to the other parameters
        specialProperties = LogParameterUtil.createPropertiesMap();
        List<Object> paramList = paramUtil.getNonSpecialPropertiesMapParameters();
        paramList.add(0, specialProperties);
        record.setParameters(paramList.toArray());

        String threadName = Thread.currentThread().getName();
        specialProperties.put(LogParameterUtil.PARAM_THREAD_NAME, threadName);

        specialProperties.put(LogParameterUtil.PARAM_PROCESSNAME, this.processName);
        specialProperties.put(LogParameterUtil.PARAM_SOURCEOBJECT, this.sourceObject);

        // Get the stack trace
        StackTraceElement stack[] = (new Throwable()).getStackTrace();
        // search for the first frame before the "Logger" class.
        int ix = 0;
        boolean foundNonLogFrame = false;
        while (ix < stack.length) {
            StackTraceElement frame = stack[ix];
            String cname = frame.getClassName();
            if (!foundNonLogFrame && !loggerClassNames.contains(cname)) {
                // We've found the relevant frame.
                record.setSourceClassName(cname);
                record.setSourceMethodName(frame.getMethodName());
                int lineNumber = frame.getLineNumber();
                specialProperties.put(LogParameterUtil.PARAM_LINE, Long.valueOf(lineNumber));
                foundNonLogFrame = true;
                if (this.callStacksToBeIgnored.isEmpty()) {
                    break; // performance optimization: avoid checking all "higher" stack frames
                }
            }
            if (foundNonLogFrame) {
                if (callStacksToBeIgnored.contains(concatenateIgnoreLogData(cname, frame.getMethodName()))) {
                    //System.out.println("Won't log record with message " + record.getMessage());
                    return;
                }
            }
            ix++;
        }
        // We haven't found a suitable frame, so just punt. This is
        // OK as we are only committed to making a "best effort" here.
    }

    StopWatch sw_afterAcsLogger = null;
    if (PROFILE) {
        sw_afterAcsLogger = sw_all.createStopWatchForSubtask("afterAcsLogger");
        LogParameterUtil logParamUtil = new LogParameterUtil(record);
        logParamUtil.setStopWatch(sw_afterAcsLogger);
    }

    // Let the delegate or Logger base class handle the rest.
    if (delegate != null) {
        delegate.log(record);
    } else {
        super.log(record);
    }

    if (PROFILE) {
        sw_afterAcsLogger.stop();
        sw_all.stop();
        long elapsedNanos = sw_all.getLapTimeNanos();
        if (profileSlowestCallStopWatch == null
                || profileSlowestCallStopWatch.getLapTimeNanos() < elapsedNanos) {
            profileSlowestCallStopWatch = sw_all;
        }
        profileLogTimeStats.addValue(elapsedNanos);
        if (profileLogTimeStats.getN() >= profileStatSize) {
            String msg = "Local logging times in ms for the last " + profileStatSize + " logs: ";
            msg += "mean=" + profileMillisecFormatter.format(profileLogTimeStats.getMean() * 1E-6);
            msg += ", median=" + profileMillisecFormatter.format(profileLogTimeStats.getPercentile(50) * 1E-6);
            msg += ", stdev="
                    + profileMillisecFormatter.format(profileLogTimeStats.getStandardDeviation() * 1E-6);
            msg += "; details of slowest log (from ";
            msg += IsoDateFormat.formatDate(profileSlowestCallStopWatch.getStartTime()) + "): ";
            msg += profileSlowestCallStopWatch.getSubtaskDetails();
            System.out.println(msg);
            profileSlowestCallStopWatch = null;
            profileLogTimeStats.clear();
        }
    }
}

From source file:com.ellychou.todo.rest.service.SpringContextJerseyTest.java

/**
* Retrieves a list of root loggers.//from w ww  .  j  av  a2  s . c  om
*
* @return list of root loggers.
*/
private Set<Logger> getRootLoggers() {
    final LogManager logManager = LogManager.getLogManager();
    final Enumeration<String> loggerNames = logManager.getLoggerNames();

    final Set<Logger> rootLoggers = Sets.newHashSet();

    while (loggerNames.hasMoreElements()) {
        Logger logger = logManager.getLogger(loggerNames.nextElement());
        if (logger != null) {
            while (logger.getParent() != null) {
                logger = logger.getParent();
            }
            rootLoggers.add(logger);
        }
    }

    return rootLoggers;
}

From source file:com.googlecode.fightinglayoutbugs.FightingLayoutBugs.java

private void enableDebugOutputToConsole(Logger logger) {
    do {//from   www . jav a  2s .co m
        for (final Handler handler : logger.getHandlers()) {
            if (handler instanceof ConsoleHandler) {
                final Level originalConsoleLogLevel = handler.getLevel();
                handler.setLevel(Level.FINE);
                _runAfterAnalysis.add(new Runnable() {
                    @Override
                    public void run() {
                        handler.setLevel(originalConsoleLogLevel);
                    }
                });
            }
        }
    } while (logger.getUseParentHandlers() && (logger = logger.getParent()) != null);
}

From source file:net.sourceforge.pmd.junit.JavaUtilLoggingRule.java

/**
 * Creates a new rule, that attaches a custom log handler
 * to the given logger./*ww  w .jav a2s . com*/
 * @param loggerName the name of the logger to check
 */
public JavaUtilLoggingRule(String loggerName) {
    this.logger = Logger.getLogger(loggerName);
    this.stream = new ByteArrayOutputStream();

    Logger currentLogger = logger;
    while (currentLogger.getHandlers().length == 0) {
        currentLogger = currentLogger.getParent();
    }
    this.customLogHandler = new StreamHandler(stream, currentLogger.getHandlers()[0].getFormatter());
}

From source file:org.ebayopensource.turmeric.eclipse.core.logging.SOALogger.java

/**
 * If the tracing is enabled, then the logging level will be setup accordingly.
 *
 * @param clazz the clazz//from  w w  w .  j av  a2 s .  co  m
 * @return An instance of <code>LogManager</code>
 */
public static synchronized SOALogger getLogger(String clazz) {
    java.util.logging.LogManager manager = java.util.logging.LogManager.getLogManager();
    Logger result = manager.getLogger(clazz);
    if (result instanceof SOALogger) {
        return (SOALogger) result;
    } else if (result != null) {//there is an existing logger instance
        if (loggers.keySet().contains(clazz)) {
            return loggers.get(clazz);
        }
        SOALogger logger = new SOALogger(clazz);
        logger.setLevel(result.getLevel());
        logger.setFilter(result.getFilter());
        logger.setParent(result.getParent());
        logger.setUseParentHandlers(logger.getUseParentHandlers());
        loggers.put(clazz, logger);
        return logger;
    } else {//can not find a logger, so let's create one.
        result = new SOALogger(clazz);
    }

    manager.addLogger(result);
    SOALogger logger = (SOALogger) manager.getLogger(clazz);
    try {
        ISOALoggingSystemProvider logSystemProvider = SOALoggingSystemExtensionRegistry.getInstance()
                .getLoggingSystemIDProvider(PluginLogDelegateHandler.getBuildSystemName());
        if (logSystemProvider != null) {
            logSystemProvider.newLoggerCreated(logger);
        }
    } catch (Exception e) {
        //ignore the issue
        e.printStackTrace();
    }
    return logger;
}