Example usage for java.util.logging LogRecord setLoggerName

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

Introduction

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

Prototype

public void setLoggerName(String name) 

Source Link

Document

Set the source Logger's name.

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 w w .j  a  v  a  2  s  .com
    }

    // 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:hudson.FunctionsTest.java

@Issue("JENKINS-20800")
@Test//from w  w w.ja  va  2 s  .com
public void printLogRecordHtml() throws Exception {
    LogRecord lr = new LogRecord(Level.INFO, "Bad input <xml/>");
    lr.setLoggerName("test");
    assertEquals("Bad input &lt;xml/&gt;\n", Functions.printLogRecordHtml(lr, null)[3]);
}

From source file:com.l2jfree.gameserver.communitybbs.Manager.RegionBBSManager.java

@Override
public void parsewrite(String ar1, String ar2, String ar3, String ar4, String ar5, L2Player activeChar) {
    if (activeChar == null)
        return;/*from  w w  w . j  a va 2s.co m*/

    if (ar1.equals("PM")) {
        final L2TextBuilder htmlCode = L2TextBuilder.newInstance();
        htmlCode.append("<html><body><br>");
        htmlCode.append(
                "<table border=0><tr><td FIXWIDTH=15></td><td align=center>L2J Community Board<img src=\"sek.cbui355\" width=610 height=1></td></tr><tr><td FIXWIDTH=15></td><td>");

        try {

            L2Player receiver = L2World.getInstance().getPlayer(ar2);
            if (receiver == null) {
                htmlCode.append(
                        "Player not found!<br><button value=\"Back\" action=\"bypass _bbsloc;playerinfo;")
                        .append(ar2).append("\" width=40 height=15 back=\"sek.cbui94\" fore=\"sek.cbui92\">");
                htmlCode.append("</td></tr></table></body></html>");
                separateAndSend(htmlCode, activeChar);
                return;
            }
            if (Config.JAIL_DISABLE_CHAT && receiver.isInJail()) {
                activeChar.sendMessage("Player is in jail.");
                return;
            }
            if (receiver.isChatBanned()) {
                activeChar.sendMessage("Player is chat banned.");
                return;
            }
            if (activeChar.isInJail() && Config.JAIL_DISABLE_CHAT) {
                activeChar.sendMessage("You cannot chat while in jail.");
                return;
            }

            if (Config.LOG_CHAT) {
                LogRecord record = new LogRecord(Level.INFO, ar3);
                record.setLoggerName("chat");
                record.setParameters(new Object[] { "TELL",
                        "[" + activeChar.getName() + " to " + receiver.getName() + "]" });
                _logChat.log(record);
            }
            CreatureSay cs = new CreatureSay(activeChar.getObjectId(), SystemChatChannelId.Chat_Tell,
                    activeChar.getName(), ar3);
            if (!BlockList.isBlocked(receiver, activeChar)) {
                if (!receiver.getMessageRefusal()) {
                    receiver.sendPacket(cs);
                    activeChar.sendPacket(new CreatureSay(activeChar.getObjectId(),
                            SystemChatChannelId.Chat_Tell, "->" + receiver.getName(), ar3));
                    htmlCode.append(
                            "Message Sent<br><button value=\"Back\" action=\"bypass _bbsloc;playerinfo;")
                            .append(receiver.getName())
                            .append("\" width=40 height=15 back=\"sek.cbui94\" fore=\"sek.cbui92\">");
                    htmlCode.append("</td></tr></table></body></html>");
                    separateAndSend(htmlCode, activeChar);
                } else {
                    activeChar.sendPacket(SystemMessageId.THE_PERSON_IS_IN_MESSAGE_REFUSAL_MODE);
                    parsecmd("_bbsloc;playerinfo;" + receiver.getName(), activeChar);
                }
            } else {
                SystemMessage sm = new SystemMessage(SystemMessageId.S1_IS_NOT_ONLINE);
                sm.addString(receiver.getName());
                activeChar.sendPacket(sm);
                sm = null;
            }
        } catch (StringIndexOutOfBoundsException e) {
            // ignore
        }
    } else {
        notImplementedYet(activeChar, ar1);
    }
}

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 w w  w  .  j  av a 2 s. 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: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);//from   w  ww. j ava2  s  .  com
    }

    //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

/**
 * Log the message at the specified level with the specified throwable if any. This method creates a LogRecord and fills in caller date before calling this
 * instance's JDK14 logger.//  w  ww.  jav  a  2 s. co  m
 */
private void log(String callerFQCN, Level level, String msg, Throwable t) {
    // millis and thread are filled by the constructor
    LogRecord record = new LogRecord(level, msg);
    record.setLoggerName(loggerName);
    record.setThrown(t);
    fillCallerData(callerFQCN, record);
    log.log(record);
}