Java Code Examples for java.util.logging.LogRecord#setThrown()

The following examples show how to use java.util.logging.LogRecord#setThrown() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JDK14LoggerAdapter.java    From HttpSessionReplacer with MIT License 6 votes vote down vote up
private LogRecord eventToRecord(LoggingEvent event, Level julLevel) {
    String format = event.getMessage();
    Object[] arguments = event.getArgumentArray();
    FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
    if (ft.getThrowable() != null && event.getThrowable() != null) {
        throw new IllegalArgumentException("both last element in argument array and last argument are of type Throwable");
    }

    Throwable t = event.getThrowable();
    if (ft.getThrowable() != null) {
        t = ft.getThrowable();
        throw new IllegalStateException("fix above code");
    }

    LogRecord record = new LogRecord(julLevel, ft.getMessage());
    record.setLoggerName(event.getLoggerName());
    record.setMillis(event.getTimeStamp());
    record.setSourceClassName(EventConstants.NA_SUBST);
    record.setSourceMethodName(EventConstants.NA_SUBST);

    record.setThrown(t);
    return record;
}
 
Example 2
Source File: LogUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
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);
    }

    //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);
}
 
Example 3
Source File: LogFormatterTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * test whether the result of LogFormatter is the same as XMLFormatter 
 * if there is no nested exception
 */
public void testXMLFormatterDifference(){
    LogRecord rec = new LogRecord(Level.SEVERE, "PROBLEM");
    LogFormatter logFormatter = new LogFormatter();
    XMLFormatter xmlFormatter = new XMLFormatter();
    String logResult = logFormatter.format(rec).replace("1000", "SEVERE");
    String xmlResult = xmlFormatter.format(rec);
    assertEquals("WITHOUT THROWABLE", xmlResult, logResult);
    rec.setThrown(new NullPointerException("TESTING EXCEPTION"));
    rec.setResourceBundleName("MUJ BUNDLE");
    logResult = logFormatter.format(rec);
    //remove file names
    logResult = logResult.replaceAll("      <file>.*</file>\n", "").replace("1000", "SEVERE");
    xmlResult = xmlFormatter.format(rec);
    assertEquals("WITH THROWABLE", xmlResult, logResult);
}
 
Example 4
Source File: LoggerJDKImpl.java    From oval with Eclipse Public License 2.0 6 votes vote down vote up
private void log(final Level level, final String msg, final Throwable t) {
   final LogRecord record = new LogRecord(level, msg);
   record.setLoggerName(name);
   record.setThrown(t);

   /* java.lang.Throwable
    *    at net.sf.oval.logging.LoggerJDKImpl.log(LoggerJDKImpl.java:123)
    *    at net.sf.oval.logging.LoggerJDKImpl.warn(LoggerJDKImpl.java:136)
    *    at net.sf.oval.internal.Log.warn(Log.java:180)
    */
   final int offset = 2;
   final StackTraceElement[] steArray = new Throwable().getStackTrace();
   record.setSourceClassName(steArray[offset].getClassName());
   record.setSourceMethodName(steArray[offset].getMethodName());

   jdkLogger.log(record);
}
 
Example 5
Source File: LoggingExceptionTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testLoggedExceptionIsPrinted() throws Exception {
    Exception ex = new IOException("Ahoj");
    LogRecord rec = new LogRecord(Level.WARNING, "Cannot process {0}");
    rec.setThrown(ex);
    rec.setParameters(new Object[] { "Jardo" });
    Logger.getLogger("global").log(rec);
    
    File[] arr = getWorkDir().listFiles();
    assertEquals("One log file", 1, arr.length);
    String s = LoggingTest.readFile(arr[0]);
    
    if (s.indexOf("Ahoj") == -1) {
        fail("There needs to be 'Ahoj':\n" + s);
    }
    if (s.indexOf("Jardo") == -1) {
        fail("There needs to be 'Jardo':\n" + s);
    }
    if (s.indexOf("testLoggedExceptionIsPrinted") == -1) {
        fail("There needs to be name of the method:\n" + s);
    }
}
 
Example 6
Source File: Log4jLogger.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
protected void append(final LoggingEvent event) {
    final LogRecord lr = new LogRecord(fromL4J(event.getLevel()),
        event.getMessage().toString());
    lr.setLoggerName(event.getLoggerName());
    if (event.getThrowableInformation() != null) {
        lr.setThrown(event.getThrowableInformation().getThrowable());
    }
    final String rbname = getResourceBundleName();
    if (rbname != null) {
        lr.setResourceBundleName(rbname);
        lr.setResourceBundle(getResourceBundle());
    }
    handler.publish(lr);
}
 
Example 7
Source File: JdkLogger.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 * 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.
 *
 * See bug report #13 for more details.
 */
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(name());
    record.setThrown(t);
    fillCallerData(callerFQCN, record);
    logger.log(record);
}
 
Example 8
Source File: LogWrapperBase.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
protected void doLog( Level level, String key, Object[] params, Class wrapperClass,
    Throwable thr )
{
    LogRecord lrec = new LogRecord( level, key ) ;
    if (params != null)
        lrec.setParameters( params ) ;
    inferCaller( wrapperClass, lrec ) ;
    lrec.setThrown( thr ) ;
    lrec.setLoggerName( loggerName );
    lrec.setResourceBundle( logger.getResourceBundle() ) ;
    logger.log( lrec ) ;
}
 
Example 9
Source File: DataflowWorkerLoggingHandlerTest.java    From beam with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and returns a LogRecord with a given message and throwable.
 *
 * @param message The message to place in the {@link LogRecord}
 * @param throwable The throwable to place in the {@link LogRecord}
 * @param params A list of parameters to place in the {@link LogRecord}
 * @return A {@link LogRecord} with the given message and throwable.
 */
private LogRecord createLogRecord(String message, Throwable throwable, Object... params) {
  LogRecord logRecord = new LogRecord(Level.INFO, message);
  logRecord.setLoggerName("LoggerName");
  logRecord.setMillis(1L);
  logRecord.setThreadID(2);
  logRecord.setThrown(throwable);
  logRecord.setParameters(params);
  return logRecord;
}
 
Example 10
Source File: VespaLogHandler.java    From vespa with Apache License 2.0 5 votes vote down vote up
/**
 * Publish a log record into the Vespa log target.
 */
public synchronized void publish(LogRecord record) {
    Level level = record.getLevel();
    String component = record.getLoggerName();

    LevelController ctrl = getLevelControl(component);
    if (!ctrl.shouldLog(level)) {
        return;
    }

    if (logRejectFilter.shouldReject(record.getMessage())) {
        return;
    }

    try {
        // provokes rotation of target
        setOutputStream(logTarget.open());
    } catch (RuntimeException e) {
        LogRecord r = new LogRecord(Level.SEVERE, "Unable to open file target");
        r.setThrown(e);
        emergencyLog(r);
        setOutputStream(System.err);
    }
    super.publish(record);
    flush();
    closeFileTarget();
}
 
Example 11
Source File: MemoryHandlerTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublishNonSerializable() {
  LogRecord logRecord = new LogRecord(Level.SEVERE, "message");
  logRecord.setThrown(new MyThrowable());
  // TODO(cjhopman): Add way for MemoryHandler publisher to be injected.
  new MemoryHandler().publish(logRecord);
}
 
Example 12
Source File: ChangeRequestBuildStrategyImpl.java    From basic-branch-build-strategies-plugin with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Restricted(ProtectedExternally.class)
@Override
public boolean isAutomaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision,
                                @CheckForNull SCMRevision lastBuiltRevision, @CheckForNull SCMRevision lastSeenRevision, @NonNull TaskListener listener) {
    if (!(head instanceof ChangeRequestSCMHead)) {
        return false;
    }
    if (ignoreTargetOnlyChanges
            && currRevision instanceof ChangeRequestSCMRevision
            && lastBuiltRevision instanceof ChangeRequestSCMRevision) {
        ChangeRequestSCMRevision<?> curr = (ChangeRequestSCMRevision<?>) currRevision;
        if (curr.isMerge() && curr.equivalent((ChangeRequestSCMRevision<?>) lastBuiltRevision)) {
            return false;
        }
    }
    try {
        if (ignoreUntrustedChanges && !currRevision.equals(source.getTrustedRevision(currRevision, listener))) {
            return false;
        }
    } catch (IOException | InterruptedException e) {
        LogRecord lr = new LogRecord(Level.WARNING,
                "Could not determine trust status for revision {0} of {1}, assuming untrusted");
        lr.setParameters(new Object[] {currRevision, head});
        lr.setThrown(e);
        Functions.printLogRecord(lr);
        return false;
    }
    return true;
}
 
Example 13
Source File: LogWrapperBase.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
protected void doLog( Level level, String key, Object[] params, Class wrapperClass,
    Throwable thr )
{
    LogRecord lrec = new LogRecord( level, key ) ;
    if (params != null)
        lrec.setParameters( params ) ;
    inferCaller( wrapperClass, lrec ) ;
    lrec.setThrown( thr ) ;
    lrec.setLoggerName( loggerName );
    lrec.setResourceBundle( logger.getResourceBundle() ) ;
    logger.log( lrec ) ;
}
 
Example 14
Source File: VespaFormatterTestCase.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public void testLowLogLevelExceptionFormatting () {
    VespaFormatter formatter = new VespaFormatter(serviceName, app);
    LogRecord r = new LogRecord(LogLevel.INFO, "meldingen her");
    r.setThrown(new IllegalStateException());
    String result = formatter.format(r);
    assertTrue(formatter.format(r).contains("meldingen her"));
}
 
Example 15
Source File: TestRunnerHandlerTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static LogRecord createRecord(Exception exception) {
    LogRecord record = new LogRecord(Level.INFO, "Hello.");
    record.setSequenceNumber(1);
    record.setInstant(Instant.ofEpochMilli(2));
    record.setThrown(exception);
    return record;
}
 
Example 16
Source File: JdkLogger.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * 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.
 *
 * See bug report #13 for more details.
 */
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(name());
    record.setThrown(t);
    fillCallerData(callerFQCN, record);
    logger.log(record);
}
 
Example 17
Source File: ClientSharedUtils.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/** returns a set of the non-loopback InetAddresses for this machine */
public static Set<InetAddress> getMyAddresses(boolean includeLocal)
    throws SocketException {
  Set<InetAddress> result = new HashSet<InetAddress>();
  Set<InetAddress> locals = new HashSet<InetAddress>();
  Enumeration<NetworkInterface> interfaces = NetworkInterface
      .getNetworkInterfaces();
  while (interfaces.hasMoreElements()) {
    NetworkInterface face = interfaces.nextElement();
    boolean faceIsUp = false;
    try {
      // invoking using JdkHelper since GemFireXD JDBC3 clients require JDK 1.5
      faceIsUp = helper.isInterfaceUp(face);
    } catch (SocketException se) {
      final Logger log = getLogger();
      if (log != null) {
        LogRecord lr = new LogRecord(Level.INFO,
            "Failed to check if network interface is up. Skipping " + face);
        lr.setThrown(se);
        log.log(lr);
      }
    }
    if (faceIsUp) {
      Enumeration<InetAddress> addrs = face.getInetAddresses();
      while (addrs.hasMoreElements()) {
        InetAddress addr = addrs.nextElement();
        if (addr.isLoopbackAddress() || addr.isAnyLocalAddress()
            || (!useLinkLocalAddresses && addr.isLinkLocalAddress())) {
          locals.add(addr);
        }
        else {
          result.add(addr);
        }
      } // while
    }
  } // while
  // fix for bug #42427 - allow product to run on a standalone box by using
  // local addresses if there are no non-local addresses available
  if (result.size() == 0) {
    return locals;
  }
  else {
    if (includeLocal) {
      result.addAll(locals);
    }
    return result;
  }
}
 
Example 18
Source File: LogShim.java    From Visage with MIT License 4 votes vote down vote up
@Override
public void info(String msg, Throwable thrown) {
	LogRecord rec = new LogRecord(Level.INFO, msg);
	rec.setThrown(thrown);
	log.log(rec);
}
 
Example 19
Source File: JdkESLogger.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
protected void internalError(String msg, Throwable cause) {
    LogRecord record = new ESLogRecord(Level.SEVERE, msg);
    record.setThrown(cause);
    logger.log(record);
}
 
Example 20
Source File: LogRecords.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void endElement(String uri, String localName, String qName) throws SAXException {
    if (current != null) {
        String v = chars.toString();
        values.put(current, v);
        if (current == Elem.PARAM) {
            if (params == null) {
                params = new ArrayList<String>();
            }
            params.add(v);
            if (params.size() > 1500) {
                LOG.severe("Too long params when reading a record. Deleting few. Msg: " + Elem.MESSAGE.parse(values)); // NOI18N
                for (String p : params) {
                    LOG.fine(p);
                }
                params.clear();
            }
        }
    }
    current = null;
    chars = new StringBuilder();
    
    if (currentEx != null && currentEx.values != null) {
        if ("frame".equals(qName)) { // NOI18N
            String line = Elem.LINE.parse(values);
            StackTraceElement elem = new StackTraceElement(
                    Elem.CLASS.parse(values),
                    Elem.METHOD.parse(values),
                    Elem.FILE.parse(values),
                    line == null ? -1 : Integer.parseInt(line)
                    );
            currentEx.trace.add(elem);
            values.remove(Elem.CLASS);
            values.remove(Elem.METHOD);
            values.remove(Elem.LINE);
        }
        if ("exception".equals(qName)) {
            currentEx.message = values.get(Elem.MESSAGE);
            String more = values.get(Elem.MORE);
            if (more != null) currentEx.more = Integer.parseInt(more);
            if (exceptions == null){
                exceptions = new ArrayDeque<FakeException>();
            }
            exceptions.add(currentEx);
            values = currentEx.values;
            currentEx = null;
        }
        return;
    }
    
    if ("record".equals(qName)) { // NOI18N
        String millis = Elem.MILLIS.parse(values);
        String seq = Elem.SEQUENCE.parse(values);
        String lev = Elem.LEVEL.parse(values);
        String thread = Elem.THREAD.parse(values);
        String msg = Elem.MESSAGE.parse(values);
        String key = Elem.KEY.parse(values);
        String catalog = Elem.CATALOG.parse(values);
        
        if (lev != null) {
            LogRecord r = new LogRecord(parseLevel(lev), key != null && catalog != null ? key : msg);
            try {
                r.setThreadID(parseInt(thread));
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, ex.getMessage(), ex);
            }
            r.setSequenceNumber(parseLong(seq));
            r.setMillis(parseLong(millis));
            r.setResourceBundleName(key);
            if (catalog != null && key != null) {
                r.setResourceBundleName(catalog);
                if (!"<null>".equals(catalog)) { // NOI18N
                    try {
                        ResourceBundle b = NbBundle.getBundle(catalog);
                        b.getObject(key);
                        // ok, the key is there
                        r.setResourceBundle(b);
                    } catch (MissingResourceException e) {
                        LOG.log(Level.CONFIG, "Cannot find resource bundle {0} for key {1}", new Object[] { catalog, key });
                        r.setResourceBundle(new FakeBundle(key, msg));
                    }
                } else {
                    LOG.log(Level.CONFIG, "Cannot find resource bundle <null> for key {1}", key);
                }
            }
            if (params != null) {
                r.setParameters(params.toArray());
            }
            if (exceptions != null) {
                r.setThrown(createThrown(null));
                // exceptions = null;  should be empty after poll
            }

            callback.publish(r);
        }

        currentEx = null;
        params = null;
        values.clear();
    }
    
}