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

The following examples show how to use java.util.logging.LogRecord#getThrown() . 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: ParserLog.java    From nmonvisualizer with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void publish(LogRecord record) {
    logBuffer.append(record.getLevel().getName());
    logBuffer.append("  ");
    logBuffer.append(record.getMessage());
    logBuffer.append("\n");

    if (record.getThrown() != null) {
        PrintWriter pw = new PrintWriter(logBuffer);
        record.getThrown().printStackTrace(pw);

        pw.close();
    }

    hasData = true;
}
 
Example 2
Source File: DebugFormatter.java    From BungeePerms with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String format(LogRecord record)
{
    StringBuilder builder = new StringBuilder();
    builder
            .append(new SimpleDateFormat("dd.MM.YYYY HH:mm:ss").format(new Date()))
            .append(": ")
            .append(record.getMessage())
            .append("\n");
    Throwable ex = record.getThrown();
    if (ex != null)
    {
        StringWriter writer = new StringWriter();
        ex.printStackTrace(new PrintWriter(writer));
        builder.append(writer);
    }
    return builder.toString();
}
 
Example 3
Source File: TextFormatter.java    From freecol with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Formats the given log record's data into human-readable text.
 * 
 * @param record The log record whose data needs to be formatted.
 * @return The log record's data as a string.
 */
@Override
public String format(LogRecord record) {
    StringBuilder result = new StringBuilder();
    result.append(record.getSourceClassName())
        .append(' ').append(record.getSourceMethodName())
        .append("\n\t").append(record.getLevel().getName())
        .append(": ").append(record.getMessage().replaceAll("\n", "\n\t"))
        .append("\n\t").append(new Date(record.getMillis()))
        .append("\n\tThread: ").append(record.getThreadID())
        .append('\n');
    if (record.getThrown() != null) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        pw.println("\tStack trace:");
        record.getThrown().printStackTrace(pw);
        pw.println("----------------------------");
        pw.flush();
        result.append(sw);
    }

    return result.toString();
}
 
Example 4
Source File: SentryErrorReporter.java    From QuickShop-Reremake with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Check if a given log record should be published.
 *
 * @param record a LogRecord
 * @return true if the log record should be published.
 */
@Override
public boolean isLoggable(@NotNull LogRecord record) {
    if (!enabled) {
        return true;
    }
    Level level = record.getLevel();
    if (level != Level.WARNING && level != Level.SEVERE) {
        return true;
    }
    if (record.getThrown() == null) {
        return true;
    }
    if (Util.isDevMode()) {
        sendError(record.getThrown(), record.getMessage());
        return true;
    } else {
        return sendError(record.getThrown(), record.getMessage()) == null;
    }
}
 
Example 5
Source File: LogFormatter.java    From VanetSim with GNU General Public License v3.0 6 votes vote down vote up
@Override 
public String format(LogRecord record) { 
    StringBuilder sb = new StringBuilder(); 
    sb.append(formatMessage(record)) 
        .append(LINE_SEPARATOR); 
    if (record.getThrown() != null) { 
        try { 
            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(); 
}
 
Example 6
Source File: LogFormatter.java    From scelight with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized String format( final LogRecord record ) {
	date.setTime( record.getMillis() );
	builder.setLength( 0 );
	
	dateStringBuffer.setLength( 0 );
	builder.append( DATE_FORMAT.format( date, dateStringBuffer, dfFieldPosition ) ).append( LEVEL_NAME_MAP.get( record.getLevel() ) );
	
	builder.append( record.getMessage() ).append( NEW_LINE );
	
	final Throwable thrown = record.getThrown();
	if ( thrown != null ) {
		final StringWriter sw = new StringWriter();
		try ( final PrintWriter pw = new PrintWriter( sw ) ) {
			thrown.printStackTrace( pw );
		}
		builder.append( sw.toString() );
	}
	
	return builder.toString();
}
 
Example 7
Source File: EnvironmentSetup.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Override
public String format(final LogRecord record) {
    final ZonedDateTime zdt =
            ZonedDateTime.ofInstant(Instant.ofEpochMilli(record.getMillis()), zone).withZoneSameInstant(utc);
    final String date = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(zdt);
    final String thread =
            record.getThreadID() == Thread.currentThread().getId() ? Thread.currentThread().getName()
                    : ("thread-" + record.getThreadID());
    final String base = '[' + date + "][" + thread + "][" + record.getLevel().getName() + "]["
            + record.getLoggerName() + "] " + record.getMessage() + System.lineSeparator();
    final String throwable;
    if (record.getThrown() != null) {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw);
        pw.println();
        record.getThrown().printStackTrace(pw);
        pw.close();
        throwable = sw.toString();
    } else {
        throwable = null;
    }
    return base + (throwable == null ? "" : throwable);
}
 
Example 8
Source File: LoggerRule.java    From jenkins-test-harness with MIT License 6 votes vote down vote up
/**
 * Initializes log record capture, in addition to merely printing it.
 * This allows you to call {@link #getRecords} and/or {@link #getMessages} later.
 * @param maximum the maximum number of records to keep (any further will be discarded)
 * @return this rule, for convenience
 */
public LoggerRule capture(int maximum) {
    messages = new ArrayList<>();
    ringHandler = new RingBufferLogHandler(maximum) {
        final Formatter f = new SimpleFormatter(); // placeholder instance for what should have been a static method perhaps
        @Override
        public synchronized void publish(LogRecord record) {
            super.publish(record);
            String message = f.formatMessage(record);
            Throwable x = record.getThrown();
            synchronized (messages) {
                messages.add(message == null && x != null ? x.toString() : message);
            }
        }
    };
    ringHandler.setLevel(Level.ALL);
    for (Logger logger : loggers.keySet()) {
        logger.addHandler(ringHandler);
    }
    return this;
}
 
Example 9
Source File: JdtLogHandler.java    From java-debug with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void publish(LogRecord record) {
    if (!isLoggable(record)) {
        return;
    }
    int severity = IStatus.INFO;
    if (record.getLevel() == Level.SEVERE) {
        severity = IStatus.ERROR;
    } else if (record.getLevel() == Level.WARNING) {
        severity = IStatus.WARNING;
    }

    IStatus status = new Status(severity, record.getLoggerName(), record.getMessage(), record.getThrown());

    Platform.getLog(JavaDebuggerServerPlugin.context.getBundle()).log(status);
}
 
Example 10
Source File: OgarServer.java    From Ogar2-Server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String format(LogRecord record) {
    StringBuilder sb = new StringBuilder(df.format(new Date(record.getMillis())));
    sb.append(" [");
    sb.append(record.getLevel());
    sb.append("] ");
    sb.append(formatMessage(record));
    sb.append('\n');
    if (record.getThrown() != null) {
        sb.append(Throwables.getStackTraceAsString(record.getThrown()));
    }
    return sb.toString();
}
 
Example 11
Source File: LogHandler.java    From Unofficial-Robinhood-Api with MIT License 5 votes vote down vote up
@Override
public void publish(LogRecord record) {
	StringBuilder builder = new StringBuilder();
	DateFormat format = new SimpleDateFormat(DATE_PATTERN);
	
	//Timestamp
	builder.append("[").append(format.format(new Date())).append("]");
	//Severity
	builder.append("[").append(record.getLevel()).append("] ");
	//Message
	builder.append(record.getMessage() + "\n");
	//Stack Trace - Error debugging is important
	Throwable trace = record.getThrown();
	
	//As long as the throwable exists, append it. Sometimes it is null
	if(trace != null) {
		
		StringWriter stackTrace = new StringWriter();
		trace.printStackTrace(new PrintWriter(stackTrace));
		builder.append(stackTrace.getBuffer());
	}
	
	System.out.println(builder.toString());
	if (writeToFile) {
		fileWriter.println(builder.toString());
	}
	
}
 
Example 12
Source File: TestLogrbResourceBundle.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void publish(LogRecord record) {
    lastBundle = record.getResourceBundle();
    lastBundleName = record.getResourceBundleName();
    lastParams = record.getParameters();
    lastThrown = record.getThrown();
    lastMessage = record.getMessage();
}
 
Example 13
Source File: Log4jLoggingHandler.java    From database with GNU General Public License v2.0 5 votes vote down vote up
public XLoggingEvent(org.apache.log4j.Logger log4jLogger,
                     LogRecord record,
                     String formattedMessage)
{
    super( "org.apache.log4j.Logger",
           log4jLogger,
           record.getMillis(),
           translateLevel(record.getLevel()),
           formattedMessage,
           record.getThrown() );

    this.origLoggerName = record.getLoggerName();
}
 
Example 14
Source File: LogRecordAdditionalInfo.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes instance of this class.
 *
 * @param logRecord
 *            LogRecord containing a <code>Throwable</code> which is an instance of
 *            {@link org.openntf.domino.exceptions.OpenNTFNotesException}
 */
public LogRecordAdditionalInfo(final LogRecord logRecord) {
	Throwable t = logRecord.getThrown();
	if (t != null && t instanceof OpenNTFNotesException) {
		exceptionDetails = ((OpenNTFNotesException) t).getExceptionDetails();
	}

	WrapperFactory wf = Factory.getWrapperFactory_unchecked();
	if (wf != null) {
		lastWrappedDocs = wf.getLastWrappedDocsInThread();
	}

}
 
Example 15
Source File: CompactFormatter.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Formats the thrown property of a LogRecord. The returned string will
 * contain a throwable message with a back trace.
 *
 * @param record the record.
 * @return empty string if nothing was thrown or formatted string.
 * @throws NullPointerException if the given record is null.
 * @see #apply(java.lang.Throwable)
 * @see #formatBackTrace(java.util.logging.LogRecord)
 */
public String formatThrown(final LogRecord record) {
    String msg;
    final Throwable t = record.getThrown();
    if (t != null) {
        String site = formatBackTrace(record);
        msg = formatMessage(t) + (isNullOrSpaces(site) ? "" : ' ' + site);
    } else {
        msg = "";
    }
    return msg;
}
 
Example 16
Source File: DefaultHandler.java    From freecol with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Publishes the given LogRecord by writing its data to a file using a
 * TextFormatter.
 * 
 * @param record The {@code LogRecord} to publish.
 */
@Override
public void publish(LogRecord record) {
    if (record.getLevel().intValue() < getLevel().intValue()
        && record.getThrown() == null) {
        return;
    }

    String str = getFormatter().format(record);
    if (consoleLogging
        && record.getLevel().intValue() >= Level.WARNING.intValue()) {
        System.err.println(str);
    }

    synchronized (this.writerLock) {
        if (this.writer != null) {
            try {
                this.writer.write(str, 0, str.length());
                // Because FreeCol is still in a very early stage.
                flush();
            } catch (IOException ioe) {
                System.err.println("Failed to write log record: " + str);
                ioe.printStackTrace(System.err);
            }
        }
    }

    // Do this last, as it might shut down a debug run
    Throwable t = record.getThrown();
    if (t != null && !(t instanceof FreeColException
            && ((FreeColException)t).debugAllowed())) {
        FreeColDebugger.handleCrash();
    }
}
 
Example 17
Source File: Installer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isAfterRestartRecord(List<LogRecord> recs) {
    for (int i = recs.size() - 1; i >= 0; i--) {
        LogRecord r = recs.get(i);
        if (r.getThrown() != null) {
            return AfterRestartExceptions.isAfterRestartRecord(r);
        }
    }
    return false;
}
 
Example 18
Source File: LogHandlerBase.java    From baratine with GNU General Public License v2.0 4 votes vote down vote up
protected String format(LogRecord record)
{
  if (! isLoggable(record)) {
    return null;
  }
  
  StringBuilder sb = new StringBuilder();
  
  if (record == null) {
    sb.append("no record");
        
    if (isNullDelimited()) {
      sb.append('\0');
    }

    return sb.toString();
  }

  try {
    Formatter formatter = getFormatter();
    
    if (formatter != null) {
      String value = formatter.format(record);

      sb.append(value).append('\n');
      
      if (isNullDelimited()) {
        sb.append('\0');
      }
        
      return sb.toString();
    }
      
    String message = record.getMessage();
    Throwable thrown = record.getThrown();
      
    if (thrown == null
        && message != null
        && message.indexOf("java.lang.NullPointerException") >= 0) {
      thrown = new IllegalStateException();
      thrown.fillInStackTrace();
    }
          
    if (thrown != null) {
      if (message != null
          && ! message.equals(thrown.toString()) 
          && ! message.equals(thrown.getMessage())) {
        printMessage(sb, message, record.getParameters());
      }
        
      StringWriter writer = new StringWriter();
      PrintWriter pw = new PrintWriter(writer);
      thrown.printStackTrace(pw);
      pw.close();
      
      sb.append(writer.toString());
    }
    else {
      printMessage(sb, message, record.getParameters());
    }

    /*
    TimestampFilter timestamp = getTimestampFilter();
    if (timestamp != null) {
      sb = timestamp.format(sb);
    }
    */
      
    if (isNullDelimited()) {
      sb.append('\0');
    }
  } catch (Throwable e) {
    e.printStackTrace();
  }

  return sb.toString();
}
 
Example 19
Source File: LogFormatter.java    From FHIR with Apache License 2.0 4 votes vote down vote up
/**
 * The standard formatter uses a horrible multiline approach. A single line
 * message is far more readable (and easier to post-process). Java 7
 * supports a (completely cryptic) format string, but we cook our own
 * food here...
 */
@Override
public String format(LogRecord lr) {
    // Don't make this static...it's not thread-safe
    SimpleDateFormat df = new SimpleDateFormat(ISO_TIME);

    // Trim the class name to the last couple of names
    String className = lr.getSourceClassName();
    // Use a max of 30 characters for our className
    if (className.length() > 30) {
        className = className.substring(className.length() - 30);
    }
    
    String thrown = "";
    if (lr.getThrown() != null) {
        thrown = lr.getThrown().getClass().getName();            
    }

    StringBuilder result = new StringBuilder();
    result.append(String.format("%1$s %7$08x %4$7s %2$30s %5$s%n", 
            df.format(new Date(lr.getMillis())), 
            className, 
            lr.getLoggerName(), 
            lr.getLevel(), 
            formatMessage(lr), 
            thrown,
            lr.getThreadID()));

    // Add the stack trace if necessary
    if (lr.getThrown() != null) {
        Throwable t = lr.getThrown();
        String msg = t.getMessage();
        if (msg != null) {
            result.append(System.lineSeparator());
            result.append(msg);
        }
        
        StringWriter sw = new StringWriter();
        t.printStackTrace(new PrintWriter(sw));
        result.append(System.lineSeparator());
        result.append(sw);
    }
    
    return result.toString();
}
 
Example 20
Source File: UIMALogFormatter.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public synchronized String format(LogRecord record) {
  // if record is null, return an empty String
  if (record == null) {
    return "";
  }

  StringBuffer buffer = new StringBuffer(100);

  // create timestamp
  Date timestamp = new Date(record.getMillis());
  String timestampStr = tsFormatter.format(timestamp);
  // append timestamp to the output string
  buffer.append(timestampStr);

  // append source thread ID
  buffer.append(" - ");
  buffer.append(record.getThreadID());

  // append source class if logrb() method was used, otherwise append logger name
  buffer.append(": ");
  if (record.getSourceClassName() == null || record.getSourceClassName().equals("")) {
    buffer.append(record.getLoggerName());
  } else {
    buffer.append(record.getSourceClassName());
  }

  // append source method if logrb() was used
  if (record.getSourceMethodName() != null) {
    buffer.append('.');
    buffer.append(record.getSourceMethodName());
  }

  // append message level
  buffer.append(": ");
  buffer.append(record.getLevel().getLocalizedName());

  // append message
  buffer.append(": ");
  buffer.append(record.getMessage());

  // append exception if avaialble
  if (record.getThrown() != null) {
    buffer.append(CRLF);
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    record.getThrown().printStackTrace(printWriter);
    printWriter.close();
    buffer.append(stringWriter.toString());
  }

  // append new line at the end
  buffer.append(CRLF);

  // return log entry
  return buffer.toString();
}