Example usage for java.util.logging LogRecord setSourceMethodName

List of usage examples for java.util.logging LogRecord setSourceMethodName

Introduction

In this page you can find the example usage for java.util.logging LogRecord setSourceMethodName.

Prototype

public void setSourceMethodName(String sourceMethodName) 

Source Link

Document

Set the name of the method that (allegedly) issued the logging request.

Usage

From source file:fr.opensagres.xdocreport.core.logging.LogUtils.java

private static void doLog(Logger log, Level level, String msg, Throwable t) {
    LogRecord record = new LogRecord(level, msg);

    record.setLoggerName(log.getName());
    record.setResourceBundleName(log.getResourceBundleName());
    record.setResourceBundle(log.getResourceBundle());

    if (t != null) {
        record.setThrown(t);//from w  ww  .  ja  va  2s  .co m
    }

    // try to get the right class name/method name - just trace
    // back the stack till we get out of this class
    StackTraceElement stack[] = (new Throwable()).getStackTrace();
    String cname = LogUtils.class.getName();
    for (int x = 0; x < stack.length; x++) {
        StackTraceElement frame = stack[x];
        if (!frame.getClassName().equals(cname)) {
            record.setSourceClassName(frame.getClassName());
            record.setSourceMethodName(frame.getMethodName());
            break;
        }
    }
    log.log(record);
}

From source file:com.machinepublishers.jbrowserdriver.JBrowserDriver.java

private static void log(Logger logger, String prefix, String message) {
    if (logger != null && !filteredLogs.contains(message)) {
        LogRecord record = null;
        if (message.startsWith(">")) {
            String[] parts = message.substring(1).split("/", 3);
            record = new LogRecord(Level.parse(parts[0]),
                    new StringBuilder().append(prefix).append(" ").append(parts[2]).toString());
            record.setSourceMethodName(parts[1]);
            record.setSourceClassName(JBrowserDriver.class.getName());
        } else {//from   ww w. ja  v a2  s .  c o  m
            record = new LogRecord(Level.WARNING,
                    new StringBuilder().append(prefix).append(" ").append(message).toString());
            record.setSourceMethodName(null);
            record.setSourceClassName(JBrowserDriver.class.getName());
        }
        logger.log(record);
    }
}

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>/*from ww  w .j a v  a  2  s . co  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:org.apache.cxf.common.logging.LogUtils.java

private static void doLog(Logger log, Level level, String msg, Throwable t) {
    LogRecord record = new LogRecord(level, msg);

    record.setLoggerName(log.getName());
    record.setResourceBundleName(log.getResourceBundleName());
    record.setResourceBundle(log.getResourceBundle());

    if (t != null) {
        record.setThrown(t);//w  w  w.  j  a v  a 2 s  .  c  o  m
    }

    //try to get the right class name/method name - just trace
    //back the stack till we get out of this class
    StackTraceElement stack[] = (new Throwable()).getStackTrace();
    String cname = LogUtils.class.getName();
    for (int x = 0; x < stack.length; x++) {
        StackTraceElement frame = stack[x];
        if (!frame.getClassName().equals(cname)) {
            record.setSourceClassName(frame.getClassName());
            record.setSourceMethodName(frame.getMethodName());
            break;
        }
    }
    log.log(record);
}

From source file:org.jretty.log.Jdk14Logger.java

/**
 * Fill in caller data if possible.//  w  w w  .j av  a  2 s .  c om
 * 
 * @param record
 *            The record to update
 */
private final void fillCallerData(String callerFQCN, LogRecord record) {
    StackTraceElement[] steArray = new Throwable().getStackTrace();
    int selfIndex = -1;
    for (int i = 0; i < steArray.length; i++) {
        final String className = steArray[i].getClassName();
        if (className.equals(callerFQCN)) {
            selfIndex = i;
            break;
        }
    }

    int found = -1;
    for (int i = selfIndex + 1; i < steArray.length; i++) {
        final String className = steArray[i].getClassName();
        if (!(className.equals(callerFQCN))) {
            found = i;
            break;
        }
    }

    if (found != -1) {
        StackTraceElement ste = steArray[found];
        // setting the class name has the side effect of setting
        // the needToInferCaller variable to false.
        record.setSourceClassName(ste.getClassName());
        record.setSourceMethodName(ste.getMethodName());
    }
}