List of usage examples for java.util.logging LogRecord getLevel
public Level getLevel()
From source file:com.cloudbees.jenkins.support.SupportLogFormatter.java
@Override @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = { "DE_MIGHT_IGNORE" }, justification = "The exception wasn't thrown on our stack frame") public String format(LogRecord record) { StringBuilder builder = new StringBuilder(); builder.append(fdf.format(new Date(record.getMillis()))); builder.append(" [id=").append(record.getThreadID()).append("]"); builder.append("\t").append(record.getLevel().getName()).append("\t"); if (record.getSourceMethodName() != null) { String sourceClass;/* w ww . jav a 2 s. c o m*/ if (record.getSourceClassName() == null) { sourceClass = record.getLoggerName(); } else { sourceClass = record.getSourceClassName(); } builder.append(abbreviateClassName(sourceClass, 32)).append("#").append(record.getSourceMethodName()); } else { String sourceClass; if (record.getSourceClassName() == null) { sourceClass = record.getLoggerName(); } else { sourceClass = record.getSourceClassName(); } builder.append(abbreviateClassName(sourceClass, 40)); } builder.append(": ").append(formatMessage(record)); if (record.getThrown() != null) { try { StringWriter writer = new StringWriter(); PrintWriter out = new PrintWriter(writer); record.getThrown().printStackTrace(out); out.close(); builder.append(writer.toString()); } catch (Exception e) { // ignore } } builder.append("\n"); return builder.toString(); }
From source file:pl.softech.learning.gwtp.simple.server.spring.RemoteLoggingHandler.java
@Override public String logOnServer(LogRecord lr) { final String strongName = getPermutationStrongName(); if (deobfuscator != null) { lr = deobfuscator.deobfuscateLogRecord(lr, strongName); }//from w ww . j av a 2s. com try { final Logger logger = LoggerFactory.getLogger(lr.getLoggerName()); LogLevel.level(lr.getLevel()).log(logger, lr); } catch (final Exception e) { LOGGER.error("Remote logging failed", e); return "Remote logging failed, check stack trace for details."; } return null; }
From source file:alma.acs.logging.adapters.JacORBFilter.java
/** * Discards less useful or misleading Jacorb logs based on the message. * <p>/*from www . j a va 2 s . c om*/ * TODO-: to improve performance, we could instead match file and line, but then would have to update * that information with the next jacorb code change. * The implementation already minimizes string comparison by checking only those messages that can occur at the given log level. * <p> * TODO: Add repeat guard based on the message, e.g. using MultipleRepeatGuard from jacsutil. */ public boolean isLoggable(LogRecord record) { String message = record.getMessage(); boolean isLoggable = true; if (record.getLevel().intValue() == Level.FINE.intValue()) { // map from FINE to FINEST if (message.startsWith("POA ") && (message.endsWith("shutdown is in progress") || message.endsWith("destruction is apparent") || message.endsWith("clear up the queue...") || message.endsWith("... done") || message.endsWith("stop the request controller") || message.endsWith("etherialize all servants ..."))) { record.setLevel(Level.FINEST); } else if (message.startsWith("get_policy_overrides returns") || message.startsWith("read GIOP message of size") || message.startsWith("wrote GIOP message of size")) { // From ACS unit tests it seems that this message is totally harmless, // caused by a Corba stub calling org.jacorb.orb.Delegate#getRelativeRoundtripTimeout() // and asking for the RELATIVE_RT_TIMEOUT_POLICY_TYPE policy. // We do not fully discard the log though because it may have other causes at the AOS. record.setLevel(Level.FINEST); // // Enable the following 2 lines to investigate for http://jira.alma.cl/browse/COMP-8302, to see where all these logs come from // String stackTrace = org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(new Throwable()); // System.out.println("Hack for COMP-8302 debugging: 'get_policy_overrides returns' message logged with trace " + stackTrace); } // from FINE to discard else isLoggable = !(message.endsWith("_invoke: queuing request") || message.indexOf("is queued (queue size:") > 0 || message.endsWith("trying to get a RequestProcessor") || message.endsWith("waiting for queue") || message.endsWith("with request processing") || // for "starts...", "ends..." message.endsWith("invokeOperation on servant (stream based)") || message.endsWith("reset a previous completion call") || message.startsWith("Delegate.getReference") || message.startsWith("Received CodeSetContext. Using") || message.startsWith("ClientConnectionManager: releasing ClientGIOPConnection") || message.startsWith("Delegate released!") || message.endsWith(": streamClosed()") // findPOA: impl_name mismatch ); } else if (record.getLevel().intValue() == Level.INFO.intValue()) { // from INFO to CONFIG if (message.indexOf("(C) The JacORB project") > 0 || message.startsWith("Received CloseConnection on ClientGIOPConnection") || message.startsWith("prepare ORB for shutdown") || message.startsWith("Client-side TCP transport to") || message.startsWith("ORB going down...") || message.startsWith("ORB run") || // also "ORB run, exit" message.equals("ORB shutdown complete") || (message.startsWith("POA ") && (message.endsWith("destroyed"))) || message.startsWith("Opened new server-side TCP/IP")) { record.setLevel(Level.CONFIG); } // from INFO to FINEST else if (message.startsWith("Connected to ") || message.startsWith("Closed server-side transport to") || (message.startsWith("POA ") && (message.endsWith("up the queue ...") || message.endsWith("... done"))) || message.startsWith("Retrying to connect to") || message.startsWith("ClientConnectionManager: created new ClientGIOPConnection") || message.startsWith("ClientConnectionManager: found ClientGIOPConnection") || message.startsWith("Initialising ORB with ID") || message.startsWith("Set default native char codeset to") || message.startsWith("Set default native wchar codeset to") || message.equals("Listener exiting") || message.equals("ConsumerTie exited")) { record.setLevel(Level.FINEST); } // from INFO to stdout shortcut else if ((message.startsWith("ClientGIOPConnection to ") || message.startsWith("ServerGIOPConnection to ")) && message.contains(" BufferDump:\n") || message.startsWith("sendMessages(): ")) { // The jacorb dumps from org.jacorb.orb.etf.StreamConnectionBase.flush() // and org.jacorb.orb.giop.GIOPConnection.getMessage() are very special. // They get enabled via properties 'jacorb.debug.dump_outgoing_messages' // and 'jacorb.debug.dump_incoming_messages' and logged as INFO. // If they are enabled, we still want to see them only in the local logs // (otherwise there may be even "positive feedback" leading to log explosion). // A cleaner concept would be to only flag this LogRecord as "log only locally", // return "isLoggable = true" and leave the rest to the local and remote log handlers. // The fact that we are dealing with a generic LogRecord (not AcsLogRecord) makes this // option also ugly though (LogParameterUtil tricks), and thus we just print and drop // the log right away here. String timeStamp = IsoDateFormat.formatDate(new Date(record.getMillis())); System.out.println(timeStamp + " " + message); isLoggable = false; } // from INFO to discard else isLoggable = !(message.startsWith("oid: ") || message.startsWith("InterceptorManager started with") || message.startsWith("Using server ID (")); } else if (record.getLevel().intValue() == Level.WARNING.intValue()) { // from WARNING to CONFIG // if (message.indexOf("") > 0) { // record.setLevel(Level.CONFIG); // } // // from WARNING to FINEST // else if (message.startsWith("")) { // record.setLevel(Level.FINEST); // } // from WARNING to discard // else isLoggable = !(message.startsWith("no adapter activator exists for") // client tries to find remote poa locally and then complains if not there... ); } else if (record.getLevel().intValue() == Level.SEVERE.intValue()) { // HSO 07-02-19: thought this adapter activator crap was logged as warning, but now it showed up in jcont test as ACS-level "Emergency", which is JDK-SEVERE isLoggable = !(message.startsWith("no adapter activator exists for") // client tries to find remote poa locally and then complains if not there... ); } // filter by possibly modified log level if (isLoggable && record.getLevel().intValue() < this.logLevel) { isLoggable = false; } // if (!isLoggable) { // System.out.println("dropping JacORB message " + message + " with Level " + record.getLevel().getName()); // } // Remove non-ascii chars from the log message, which seems to occur only in logs coming from jacorb, // see http://jira.alma.cl/browse/COMP-3243 // For simplicity we blank all non-ascii-7-printable chars except newline and tab, // at the low risk of erroneously blanking more sophisticated (Umlaut etc) chars that jacorb may send us. // If that turns out to be the case, and the encoding turns out as unicode, then see http://en.wikipedia.org/wiki/C0_and_C1_control_codes if (isLoggable && message != null) { String message2 = null; int mlen = message.length(); for (int i = 0; i < mlen; i++) { char ch = message.charAt(i); if ((ch < 32 || ch >= 127) && ch != '\n' && ch != '\t') { // got a bad char if (message2 == null) { // copy the leading good chars only if needed, to improve performance message2 = message.substring(0, i); } // blank the bad char message2 += '#'; } else if (message2 != null) { message2 += ch; } } if (message2 != null) { record.setMessage(message2); } } return isLoggable; }
From source file:com.valygard.aohruthless.Joystick.java
/** * Not satisfied with global logging, which can become cluttered and messy * with many plugins or players using commands, etc, the Bukkit logger will * log all relevant information to a log file. This log file can be found in * the plugin data folder, in the subdirectory <i>logs</i>. * <p>/*from w w w .j ava 2s.c o m*/ * The log file, <i>joystick.log</i>, will not be overriden. The logger will * simply append new information if the file already exists. All messages * will be logged in the format:<br> * [month-day-year hr-min-sec] (level): (message), where level is the * {@link LogRecord#getLevel()} and the message is the * {@link LogRecord#getMessage()}. * </p> * * @return the created FileHandler, null if a SecurityException or * IOException were thrown and handled. */ private FileHandler setupLogger() { File dir = new File(getDataFolder() + File.separator + "logs"); dir.mkdirs(); try { FileHandler handler = new FileHandler(dir + File.separator + "joystick.log", true); getLogger().addHandler(handler); handler.setFormatter(new SimpleFormatter() { @Override public String format(LogRecord record) { Date date = new Date(); SimpleDateFormat df = new SimpleDateFormat("[MM-dd-yyyy HH:mm:ss]"); return df.format(date) + " " + record.getLevel() + ":" // org.apache.commons.lang + StringUtils.replace(record.getMessage(), "[Joystick]", "") + System.getProperty("line.separator"); } }); return handler; } catch (SecurityException | IOException e) { e.printStackTrace(); return null; } }
From source file:io.stallion.services.LogFormatter.java
@Override public String format(LogRecord record) { StringBuilder sb = new StringBuilder(); SimpleDateFormat df = new SimpleDateFormat("MMM dd HH:mm:ss"); String dateString = df.format(new Date(record.getMillis())); String classAndMethod = record.getSourceClassName() + "." + record.getSourceMethodName() + " "; classAndMethod = StringUtils.rightPad(classAndMethod, 50); sb.append(dateString).append(" ").append(record.getLevel().getLocalizedName()).append(" ") .append(classAndMethod).append(formatMessage(record)).append(LINE_SEPARATOR); if (record.getThrown() != null) { try {//www .ja v a2s . com StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); record.getThrown().printStackTrace(pw); pw.close(); sb.append(sw.toString()); } catch (Exception ex) { // ignore } } return sb.toString(); }
From source file:NemaLogFormatter.java
/** Formats the record. * // ww w .java2 s . c om * @param record The log record to format * @return The formated record */ @Override public String format(LogRecord record) { String className = record.getSourceClassName(); String threadName = Thread.currentThread().getName(); if (threadName != null && threadName.length() > MAX_THREAD_NAME_LENGTH) { threadName = threadName.substring(threadName.length() - MAX_THREAD_NAME_LENGTH); } String sTimeStamp = FORMATER.format(new Date(record.getMillis())); return sTimeStamp + "::" + record.getLevel() + ": " + record.getMessage() + " " + ((bClass) ? " [" + className + "." + record.getSourceMethodName() + "]" : "") + ((bClass) ? " <" + threadName + ":" + record.getThreadID() + ">" : "") + NEW_LINE; }
From source file:majordodo.task.BrokerTestUtils.java
@Before public void brokerTestUtilsBefore() throws Exception { // Setup exception handler Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override// w w w . j a va 2 s.c o m public void uncaughtException(Thread t, Throwable e) { System.err.println("uncaughtException from thread " + t.getName() + ": " + e); e.printStackTrace(); unhandledExceptions.add(e); } }); // Setup Logger System.out.println("Setup logger to level " + logLevel.getName()); java.util.logging.LogManager.getLogManager().reset(); ConsoleHandler ch = new ConsoleHandler(); ch.setLevel(logLevel); ch.setFormatter(new Formatter() { @Override public String format(LogRecord record) { return "" + new java.sql.Timestamp(record.getMillis()) + " " + record.getLevel() + " [" + getThreadName(record.getThreadID()) + "<" + record.getThreadID() + ">] " + record.getLoggerName() + ": " + formatMessage(record) + "\n"; } }); java.util.logging.Logger.getLogger("").setLevel(logLevel); java.util.logging.Logger.getLogger("").addHandler(ch); // Initialize groupsMap groupsMap.clear(); groupsMap.put(userId, group); // Setup workdir Path mavenTargetDir = Paths.get("target").toAbsolutePath(); workDir = Files.createTempDirectory(mavenTargetDir, "test" + System.nanoTime()); if (startBroker) { broker = new Broker(brokerConfig, new FileCommitLog(workDir, workDir, 1024 * 1024), new TasksHeap(1000, createTaskPropertiesMapperFunction())); broker.startAsWritable(); server = new NettyChannelAcceptor(broker.getAcceptor()); server.start(); } if (startReplicatedBrokers) { zkServer = new ZKTestEnv(folderZk.getRoot().toPath()); zkServer.startBookie(); // Broker 1 broker1 = new Broker(broker1Config, new ReplicatedCommitLog(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath(), folderSnapshots.newFolder().toPath(), BrokerHostData.formatHostdata( new BrokerHostData(broker1Host, broker1Port, "", false, null)), false), new TasksHeap(1000, createTaskPropertiesMapperFunction())); broker1.startAsWritable(); server1 = new NettyChannelAcceptor(broker1.getAcceptor(), broker1Host, broker1Port); server1.start(); // Broker 2 broker2 = new Broker(broker2Config, new ReplicatedCommitLog(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath(), folderSnapshots.newFolder().toPath(), BrokerHostData.formatHostdata( new BrokerHostData(broker2Host, broker2Port, "", false, null)), false), new TasksHeap(1000, createTaskPropertiesMapperFunction())); broker2.start(); server2 = new NettyChannelAcceptor(broker2.getAcceptor(), broker2Host, broker2Port); server2.start(); // Broker locator brokerLocator = new ZKBrokerLocator(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath()); } }
From source file:com.ellychou.todo.rest.service.SpringContextJerseyTest.java
/** * Retrieves {@link Handler log handler} capable of storing {@link LogRecord logged records}. * * @return log handler.//from www . j av a2 s . c om */ private Handler getLogHandler() { if (logHandler == null) { final Integer logLevel = Integer.valueOf(getProperty(TestProperties.RECORD_LOG_LEVEL)); logHandler = new Handler() { @Override public void publish(LogRecord record) { final String loggerName = record.getLoggerName(); if (record.getLevel().intValue() >= logLevel && loggerName.startsWith("org.glassfish.jersey") && !loggerName.startsWith("org.glassfish.jersey.test")) { loggedRuntimeRecords.add(record); } } @Override public void flush() { } @Override public void close() throws SecurityException { } }; } return logHandler; }
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 a2 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.fornax.cartridges.sculptor.smartclient.server.util.UnifiedFormatter.java
@Override public String format(LogRecord record) { String username = "ANONYMOUS"; if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null && SecurityContextHolder.getContext().getAuthentication().getPrincipal() != null) { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof User) { username = ((User) principal).getUsername(); } else {//from w ww.j av a 2s . co m username = principal.toString(); } } int dotIndex = record.getSourceClassName().lastIndexOf("."); String className = record.getSourceClassName().substring(dotIndex != -1 ? dotIndex + 1 : 0); String msg = record.getMessage(); if (record.getParameters() != null && record.getParameters().length > 0) { msg = MessageFormat.format(record.getMessage(), record.getParameters()); } if (record.getThrown() != null) { Throwable thrown = record.getThrown(); StringWriter result = new StringWriter(); thrown.printStackTrace(new PrintWriter(result)); result.flush(); msg += "\n" + result.getBuffer(); } return FST + dateFormat.format(record.getMillis()) + FET + FSEP + RST + FST + record.getLevel() + FET + FSEP + FST + className + "." + record.getSourceMethodName() + FET + FSEP + FST + username + FET + FSEP + FST + record.getThreadID() + FET + FSEP + FST + msg + FET + RET; }