@Override
  public String format(LogRecord record) {

    int count = Thread.activeCount();

    Thread th[] = new Thread[count];
    // returns the number of threads put into the array
    Thread.enumerate(th);

    String thrName = null;

    // prints active threads
    for (int i = 0; i < count; i++) {

      if (th[i] != null && th[i].getId() == record.getThreadID()) {

        thrName = th[i].getName();
        break;
      }
    }

    if (thrName == null) {
      thrName = String.format("id:%d", record.getThreadID());
    }

    StringBuilder sb = new StringBuilder();

    sb.append(new Date(record.getMillis()))
        .append(" ")
        .append(record.getLevel().getLocalizedName())
        .append(" ")
        .append("[")
        .append(record.getSourceClassName())
        .append("]")
        .append("{")
        .append(thrName)
        .append("}: ")
        .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 "RT: " + sb.toString();
  }
    @Override
    public String format(LogRecord record) {

      StringBuilder stringBuilder = new StringBuilder("[");
      stringBuilder.append(simpleDateFormat.format(new Date(record.getMillis()))).append("]");
      stringBuilder.append(" [TID:").append(getThreadId()).append("] [");
      stringBuilder.append(getCallingInfo(7));
      stringBuilder
          .append("[")
          .append(record.getLevel().getLocalizedName())
          .append("]: ")
          .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();
          stringBuilder.append(sw.toString());
        } catch (Exception ex) {
          // ignore
        }
      }

      return stringBuilder.toString();
    }
 @Override
 @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
 public synchronized String format(final LogRecord record) {
   dat.setTime(record.getMillis());
   String source;
   if (record.getSourceClassName() != null) {
     source = record.getSourceClassName();
     if (record.getSourceMethodName() != null) {
       source += "#" + record.getSourceMethodName();
     }
   } else {
     source = record.getLoggerName();
   }
   String message = formatMessage(record);
   String throwable = "";
   if (record.getThrown() != null) {
     StringWriter sw = new StringWriter();
     PrintWriter pw = new PrintWriter(sw);
     pw.println();
     record.getThrown().printStackTrace(pw);
     pw.close();
     throwable = sw.toString();
   }
   return String.format(
       FORMAT,
       dat,
       source,
       record.getLoggerName(),
       record.getLevel().getLocalizedName(),
       message,
       throwable);
 }
  @Override
  public String format(LogRecord record) {
    ChatArguments args = LOG_TEMPLATE.getArguments();
    ChatArguments level = colorizeLevel(record.getLevel());
    args.setPlaceHolder(LEVEL, level);
    if (record instanceof FormattedLogRecord) {
      args.setPlaceHolder(MESSAGE, ((FormattedLogRecord) record).getFormattedMessage());
    } else {
      args.setPlaceHolder(MESSAGE, new ChatArguments(super.formatMessage(record) + '\n'));
    }

    if (record.getThrown() != null) {
      StringWriter writer = new StringWriter();
      record.getThrown().printStackTrace(new PrintWriter(writer));
      String[] lines = writer.getBuffer().toString().split("\n");
      for (String line : lines) {
        args.append(
            LOG_TEMPLATE
                .getArguments()
                .setPlaceHolder(LEVEL, level)
                .setPlaceHolder(MESSAGE, new ChatArguments(line))
                .asString(handlerId));
        args.append('\n');
      }
    }
    args.append(ChatStyle.RESET);
    return args.asString(handlerId);
  }
Exemple #5
0
  @Override
  public String format(LogRecord event) {
    final StringBuilder html = new StringBuilder();
    html.append(getHtmlPrefix(event));
    html.append(getRecordInfo(event, "<br>"));
    html.append(getEscaped(event.getMessage()));
    if (showStackTraces && event.getThrown() != null) {
      html.append("<br>");
      event
          .getThrown()
          .printStackTrace(
              new StackTracePrintStream(html) {
                @Override
                public void append(String str) {
                  html.append(getEscaped(str));
                }

                @Override
                public void newLine() {
                  html.append("<br>");
                }
              });
    }
    html.append(getHtmlSuffix(event));
    return html.toString();
  }
Exemple #6
0
  @Override
  public String format(LogRecord record) {
    StringBuilder sb = new StringBuilder();

    sb.append(new SimpleDateFormat("HH:mm:ss").format(new Date(record.getMillis())))
        .append(" ")
        .append(record.getLevel().getLocalizedName())
        .append(": ")
        .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();
  }
Exemple #7
0
  public synchronized String format(LogRecord record) {
    StringBuffer sb = new StringBuffer();
    date.setTime(record.getMillis() + timeDiff);
    sb.append(dFormat.format(date));
    if (isShowingThreads) {
      Thread currentThread = Thread.currentThread();
      if (currentThread != lastThread) {
        lastThread = currentThread;
        lastThreadName = currentThread.getName();
      }
      sb.append(" [").append(lastThreadName).append(']');
    }
    sb.append(' ')
        .append(record.getLevel())
        .append(' ')
        .append(getAliasFor(record.getLoggerName()))
        .append('|')
        .append(record.getMessage())
        .append(EOL);

    if (record.getThrown() != null) {
      try {
        StringWriter out = new StringWriter();
        PrintWriter pout = new PrintWriter(out);
        record.getThrown().printStackTrace(pout);
        pout.close();
        sb.append(out.toString());
      } catch (Exception e) {
        // Ignore any errors while extracting stack trace
      }
    }

    return sb.toString();
  }
 @Override
 public void publish(LogRecord record) {
   if ((record.getLevel().intValue() > Level.INFO.intValue())
       && thrown == null
       && record.getThrown() != null) {
     thrown = record.getThrown();
   }
 }
  private LogRecord deobfuscateLogRecord(
      StackTraceDeobfuscator deobfuscator, LogRecord lr, String strongName) {
    if (lr.getThrown() != null && strongName != null) {
      deobfuscator.deobfuscateStackTrace(lr.getThrown(), strongName);
    }

    return lr;
  }
Exemple #10
0
 /**
  * Log a LogRecord.
  *
  * @param record The LogRecord to be published
  */
 @Override
 public void log(LogRecord record) {
   if (record.getThrown() != null) {
     getContext().log(record.getMessage(), record.getThrown());
   } else {
     getContext().log(record.getMessage());
   }
 }
 /**
  * @param record
  * @param sb
  */
 private void printException(LogRecord record, StringBuffer sb) {
   if (record.getThrown() != null) {
     try {
       StringWriter sw = new StringWriter();
       PrintWriter pw = new PrintWriter(sw);
       record.getThrown().printStackTrace(pw);
       pw.close();
       sb.append(lineSeparator);
       sb.append(sw.toString());
       sb.append(lineSeparator);
     } catch (Exception ex) {
     }
   }
 }
Exemple #12
0
 @Override
 public String format(LogRecord record) {
   Date date = new Date(record.getMillis());
   String message = record.getMessage();
   String output =
       date.toString() + " --> " + message + System.getProperty("line.separator");
   if (record.getThrown() != null) {
     output +=
         "\tCause: "
             + record.getThrown().getMessage()
             + System.getProperty("line.separator");
   }
   return output;
 }
  private void send(final LogRecord record) {
    final MetaData data = new MetaData();
    if (plugin.getServerInformation() != null) {
      data.put("account_id", plugin.getServerInformation().getAccount().getId());
      data.put("server_id", plugin.getServerInformation().getServer().getId());
      data.put("platform", "bukkit");
    }

    if (record.getLevel() == Level.SEVERE) {
      client.notify(record.getThrown(), "error", data);
    } else if (record.getLevel() == Level.WARNING) {
      client.notify(record.getThrown(), "warning", data);
    }
  }
Exemple #14
0
 protected void callPlainSLF4JLogger(@Nonnull Logger slf4jLogger, LogRecord record) {
   final String i18nMessage = getMessageI18N(record);
   final int julLevelValue = record.getLevel().intValue();
   if (julLevelValue <= TRACE_LEVEL_THRESHOLD) {
     slf4jLogger.trace(i18nMessage, record.getThrown());
   } else if (julLevelValue <= DEBUG_LEVEL_THRESHOLD) {
     slf4jLogger.debug(i18nMessage, record.getThrown());
   } else if (julLevelValue <= INFO_LEVEL_THRESHOLD) {
     slf4jLogger.info(i18nMessage, record.getThrown());
   } else if (julLevelValue <= WARN_LEVEL_THRESHOLD) {
     slf4jLogger.warn(i18nMessage, record.getThrown());
   } else {
     slf4jLogger.error(i18nMessage, record.getThrown());
   }
 }
Exemple #15
0
  public String format(LogRecord record) {
    StringBuffer line = new StringBuffer();

    switch (type) {
      case FILE:
        line.append(currentDateString());
        line.append(" - ");
        line.append(record.getLevel().getName());
        line.append(" - ");
        line.append(record.getMessage());
        line.append(LF);
        break;

      case CONSOLE:
      default:
        line.append(record.getMessage());
        line.append(LF);
        break;
    }

    Throwable thrown = record.getThrown();
    if (thrown != null) {
      line.append(toString(thrown));
    }

    return line.toString();
  }
  /*
   * (non-Javadoc)
   *
   * @see java.util.logging.Formatter#format(java.util.logging.LogRecord)
   */
  @Override
  public String format(final LogRecord logRecord) {
    //		Date recordDate = new Date(logRecord.getMillis());
    StringBuffer sb = new StringBuffer();
    try {
      // TIME and LEVEL is already at the console
      //			sb.append(LogUtils.dateToString(recordDate, UTC_Format));
      //			sb.append(" [");
      //			sb.append(logRecord.getLevel().getName());
      //			sb.append("]: ");

      //
      sb.append(logRecord.getMessage());

      sb.append("\n   (source:");
      sb.append(logRecord.getSourceClassName());
      sb.append('.');
      sb.append(logRecord.getSourceMethodName());
      if (logRecord.getThrown() != null) {
        sb.append(" - See IBM_TECHNICAL_SUPPORT\\org.openntf.log.X.Y.txt for full stack trace.");
      }
      sb.append(")");
    } catch (Throwable t) {
      System.out.println(
          "Error trying to format output for error handling. Resorting to standard stack trace...");
      t.printStackTrace();
    }
    return sb.toString();
  }
 public synchronized String format(LogRecord r) {
   if (r.getThrown() != null) {
     errors++;
   }
   count++;
   return "";
 }
  private void testResumeException(final String path, final String entity) throws Exception {
    final WebTarget errorResource = target("errorResource");

    final Future<Response> suspended = errorResource.path("suspend").request().async().get();
    final Response response = errorResource.path(path).request().get();

    assertThat(response.getStatus(), equalTo(200));
    assertThat(response.readEntity(String.class), equalTo("ok"));

    final Response suspendedResponse = suspended.get();

    assertThat(suspendedResponse.getStatus(), equalTo(500));
    if (entity != null) {
      assertThat(suspendedResponse.readEntity(String.class), equalTo(entity));
    }

    suspendedResponse.close();

    // Check there is no NPE.
    for (final LogRecord record : getLoggedRecords()) {
      final Throwable thrown = record.getThrown();
      if (thrown != null && thrown instanceof NullPointerException) {
        fail("Unexpected NPE.");
      }
    }
  }
Exemple #19
0
  @Override
  public void publish(LogRecord record) {
    final Map<String, Object> map = Loggly.getMap();

    String level = "UNKN";
    if (record.getLevel().equals(Level.WARNING)) {
      level = "WARN";
    } else if (record.getLevel().equals(Level.SEVERE)) {
      level = "SEVR";
    } else if (record.getLevel().equals(Level.INFO)) {
      level = "INFO";
    } else if (record.getLevel().equals(Level.FINE)) {
      level = "FINE";
    } else if (record.getLevel().equals(Level.FINEST)) {
      level = "FNST";
    } else if (record.getLevel().equals(Level.FINER)) {
      level = "FINR";
    } else if (record.getLevel().equals(Level.CONFIG)) {
      level = "CONF";
    } else if (record.getLevel().equals(Level.OFF)) {
      level = "OFF ";
    } else if (record.getLevel().equals(Level.ALL)) {
      level = "ALL ";
    }

    // and the log message itself
    if (record.getParameters() != null && record.getParameters().length > 0) {
      java.util.Formatter formatter = new java.util.Formatter();
      formatter.format(record.getMessage(), record.getParameters());
      map.put("message", formatter.toString());
    } else {
      map.put("message", record.getMessage());
    }

    // finally, other metadata
    map.put("thread", Thread.currentThread().getName());
    map.put("loggerName", record.getLoggerName());
    map.put("level", level);

    if (record.getThrown() != null) {
      StringWriter sw = new StringWriter();
      record.getThrown().printStackTrace(new PrintWriter(sw));
      map.put("stackTrace", sw.toString());
    }

    pool.submit(new LogglySample(map));
  }
  @Override
  public void publish(LogRecord record) {
    if (record.getThrown() == null) {
      return;
    }

    // Otherwise, see if this error is caused by the Buycraft plugin.
    // THIS DETECTION IS NOT PERFECT, but should catch most cases.
    if (record.getThrown() instanceof UnhandledException) {
      if (record.getThrown().getMessage() != null
          && TASK.matcher(record.getThrown().getMessage()).find()) {
        send(record);
        return;
      }
    }

    if (record.getThrown() instanceof CommandException) {
      if (record.getThrown().getMessage() != null
          && COMMAND.matcher(record.getThrown().getMessage()).find()) {
        send(record);
        return;
      }
    }

    if (record.getMessage() != null && LISTENER.matcher(record.getMessage()).find()) {
      send(record);
      return;
    }
  }
  protected final void appendThrown(LogRecord record, TextBuilder tb) {
    if (record.getThrown() != null) {
      StringWriter sw = null;
      PrintWriter pw = null;
      try {
        sw = new StringWriter();
        pw = new PrintWriter(sw);

        record.getThrown().printStackTrace(pw);

        appendNewline(tb);
        tb.append(sw);
      } finally {
        IOUtils.closeQuietly(pw);
        IOUtils.closeQuietly(sw);
      }
    }
  }
 /**
  * Updates the summary statistics but does not store the given LogRecord.
  *
  * @param record the LogRecord used to collect statistics.
  */
 private synchronized void accept(final LogRecord record) {
   final long millis = record.getMillis();
   minMillis = Math.min(minMillis, millis);
   maxMillis = Math.max(maxMillis, millis);
   ++count;
   if (record.getThrown() != null) {
     ++thrown;
   }
 }
Exemple #23
0
    @Override
    public String format(LogRecord record) {
      StringBuilder builder = new StringBuilder();

      builder.append(date.format(record.getMillis()));
      builder.append(" [");
      builder.append(record.getLevel().getLocalizedName().toUpperCase());
      builder.append("] ");
      builder.append(colorize(formatMessage(record)));
      builder.append('\n');

      if (record.getThrown() != null) {
        StringWriter writer = new StringWriter();
        record.getThrown().printStackTrace(new PrintWriter(writer));
        builder.append(writer.toString());
      }

      return builder.toString();
    }
  @AdviseWith(adviceClasses = {PropsUtilAdvice.class})
  @Test
  public void testShutdownFailWithLog() throws NoSuchObjectException {
    UnicastRemoteObject.unexportObject(_getMPIImpl(), true);

    final IOException ioException = new IOException();

    ReflectionTestUtil.setFieldValue(
        MPIHelperUtil.class,
        "_intraband",
        new MockIntraband() {

          @Override
          public void close() throws IOException {
            throw ioException;
          }
        });

    try (CaptureHandler captureHandler =
        JDKLoggerTestUtil.configureJDKLogger(MPIHelperUtil.class.getName(), Level.WARNING)) {

      MPIHelperUtil.shutdown();

      List<LogRecord> logRecords = captureHandler.getLogRecords();

      Assert.assertEquals(2, logRecords.size());

      LogRecord logRecord = logRecords.get(0);

      logRecord = logRecords.get(0);

      Assert.assertEquals("Unable to unexport " + _getMPIImpl(), logRecord.getMessage());

      Throwable throwable = logRecord.getThrown();

      Assert.assertSame(NoSuchObjectException.class, throwable.getClass());

      logRecord = logRecords.get(1);

      Assert.assertEquals("Unable to close intraband", logRecord.getMessage());
      Assert.assertSame(ioException, logRecord.getThrown());
    }
  }
  @Override
  public String format(LogRecord record) throws RemoteException, RemoteException {
    StringBuilder sb = new StringBuilder();

    // Timestamp
    addTimestamp(sb, record.getMillis());

    // Severity
    sb.append(' ');
    sb.append(record.getLevel());

    // Thread
    sb.append(' ');
    sb.append('[');
    sb.append(Thread.currentThread().getName());
    sb.append(']');

    // Source
    sb.append(' ');
    sb.append(record.getSourceClassName());
    sb.append('.');
    sb.append(record.getSourceMethodName());

    // Message
    sb.append(' ');
    sb.append(formatMessage(record));

    // Stack trace
    if (record.getThrown() != null) {
      sb.append(ST_SEP);
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      record.getThrown().printStackTrace(pw);
      pw.close();
      sb.append(sw.getBuffer());
    }

    // New line for next record
    sb.append(LINE_SEP);

    return sb.toString();
  }
  /**
   * Format the given LogRecord.
   *
   * @param record the log record to be formatted.
   * @return a formatted log record
   */
  public synchronized String format(LogRecord record) {
    StringBuilder sb = new StringBuilder();

    sb.append(formatMessage(record));
    sb.append('\n');

    if (record.getThrown() != null) {
      try {
        sb.append(System.getProperty("line.separator"));
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        record.getThrown().printStackTrace(pw);
        pw.close();
        sb.append(sw.toString());
      } catch (Exception ex) {
      }
    }

    return sb.toString();
  }
 @Override
 public String format(LogRecord logRecord) {
   Object[] arguments = new Object[6];
   arguments[0] = logRecord.getThreadID();
   String fullClassName = logRecord.getSourceClassName();
   int lastDot = fullClassName.lastIndexOf('.');
   String className = fullClassName.substring(lastDot + 1);
   arguments[1] = className;
   arguments[2] = logRecord.getSourceMethodName();
   arguments[3] = new Date(logRecord.getMillis());
   arguments[4] = logRecord.getMessage();
   if (logRecord.getThrown() != null) {
     Writer result = new StringWriter();
     logRecord.getThrown().printStackTrace(new PrintWriter(result));
     arguments[5] = result.toString();
   } else {
     arguments[5] = "";
   }
   return messageFormat.format(arguments);
 }
 @Override
 public void log(LogEvent logEvent) {
   LogRecord logRecord = logEvent.getLogRecord();
   if (logRecord.getLevel() == Level.OFF) {
     return;
   }
   String name = logEvent.getLogRecord().getLoggerName();
   org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(name);
   org.apache.log4j.Level level = toLog4jLevel(logRecord.getLevel());
   String message = logRecord.getMessage();
   Throwable throwable = logRecord.getThrown();
   logger.callAppenders(new LoggingEvent(name, logger, level, message, throwable));
 }
  /**
   * Format the given LogRecord.
   *
   * @param record the log record to be formatted.
   * @return a formatted log record
   */
  @Override
  public synchronized String format(LogRecord record) {
    StringBuffer sb = m_buffer;
    sb.setLength(0);

    m_timestamp.setTime(record.getMillis());
    String tmp = record.getSourceClassName();
    m_args[1] = tmp == null ? record.getLoggerName() : tmp;
    m_args[2] = formatMessage(record);
    s_tsFormatter.format(m_args, sb, null);

    Throwable thrown = record.getThrown();
    if (thrown != null) {
      sb.append(s_lineSeparator);
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      record.getThrown().printStackTrace(pw);
      pw.close();
      sb.append(sw.toString());
    }
    return sb.toString();
  }
  @Override
  public String format(LogRecord record) {

    String stackTrace = "";
    Throwable throwable = record.getThrown();
    if (throwable != null) {
      StringWriter sw = new StringWriter();
      throwable.printStackTrace(new PrintWriter(sw));
      stackTrace = sw.toString();
    }

    int lineNo;
    StackTraceElement[] stack = Thread.currentThread().getStackTrace();
    if (throwable != null && stack.length > 7) lineNo = stack[7].getLineNumber();
    else if (stack.length > 8) lineNo = stack[8].getLineNumber();
    else lineNo = -1;

    StringBuffer b = new StringBuffer();
    if (logPolicy.isEnabled(LogPolicy.LOG_POLICY_SHOW_THREAD_ID)) {
      b.append(String.format("%2d", record.getThreadID())).append(" ");
    }
    if (logPolicy.isEnabled(LogPolicy.LOG_POLICY_SHOW_LEVEL)) {
      b.append(record.getLevel().toString()).append(" ");
    }
    if (logPolicy.isEnabled(LogPolicy.LOG_POLICY_SHOW_CLASS)) {
      b.append("[").append(getSimpleClassName(record.getSourceClassName())).append("]: ");
    }
    if (logPolicy.isEnabled(LogPolicy.LOG_POLICY_SHOW_MESSAGE)) {
      b.append(formatMessage(record));
    }
    if (logPolicy.isEnabled(LogPolicy.LOG_POLICY_SHOW_SOURCE)) {
      b.append(" - (")
          .append(record.getSourceClassName())
          .append(".java:")
          .append(lineNo)
          .append(") ");
    }
    if (logPolicy.isEnabled(LogPolicy.LOG_POLICY_SHOW_METHOD)) {
      b.append(record.getSourceMethodName()).append("()");
    }
    if (logPolicy.isEnabled(LogPolicy.LOG_POLICY_SHOW_THREAD)) {
      b.append(" in thread ").append(Thread.currentThread().getName());
    }
    if (logPolicy.dateFormat != null) {
      b.append(" at (")
          .append(logPolicy.dateFormat.format(new Date(record.getMillis())))
          .append(")");
    }
    b.append("\n").append(stackTrace);
    return b.toString();
  }