@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;
    }
  }
    public synchronized void publish(LogRecord rec) {
      if ("133616 - checking invalid".equals(rec.getMessage())) {
        Thread lockingThread =
            new Thread(
                new Runnable() {

                  public void run() {
                    try {
                      fileObject.lock().releaseLock();
                    } catch (IOException ex) {
                      fail(ex.getMessage());
                    }
                  }
                },
                "Locking");
        lockingThread.start();
        try {
          wait();
        } catch (InterruptedException ex) {
          fail(ex.getMessage());
        }
      }
      if ("133616 - in lock".equals(rec.getMessage())) {
        notify();
      }
    }
Example #3
0
  public static void testLoggingSuppressor() throws IOException {
    TestLogHandler logHandler = new TestLogHandler();

    Closeables.logger.addHandler(logHandler);
    try {
      Closer closer = new Closer(new Closer.LoggingSuppressor());

      TestCloseable c1 = closer.register(TestCloseable.throwsOnClose(new IOException()));
      TestCloseable c2 = closer.register(TestCloseable.throwsOnClose(new RuntimeException()));
      try {
        throw closer.rethrow(new IOException("thrown"), IOException.class);
      } catch (IOException expected) {
      }

      assertTrue(logHandler.getStoredLogRecords().isEmpty());

      closer.close();

      assertEquals(2, logHandler.getStoredLogRecords().size());

      LogRecord record = logHandler.getStoredLogRecords().get(0);
      assertEquals("Suppressing exception thrown when closing " + c2, record.getMessage());

      record = logHandler.getStoredLogRecords().get(1);
      assertEquals("Suppressing exception thrown when closing " + c1, record.getMessage());
    } finally {
      Closeables.logger.removeHandler(logHandler);
    }
  }
Example #4
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();
  }
  @AdviseWith(adviceClasses = PropsUtilAdvice.class)
  @Test
  public void testInvalidSettingWithLog() {
    CaptureHandler captureHandler = _doTestInvalidSetting(Level.WARNING);

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

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

      LogRecord logRecord1 = logRecords.get(0);

      Assert.assertEquals(
          PropsKeys.BUFFERED_INCREMENT_THREADPOOL_KEEP_ALIVE_TIME + "[]=-3. Auto reset to 0.",
          logRecord1.getMessage());

      LogRecord logRecord2 = logRecords.get(1);

      Assert.assertEquals(
          PropsKeys.BUFFERED_INCREMENT_THREADPOOL_MAX_SIZE + "[]=-4. Auto reset to 1.",
          logRecord2.getMessage());
    } finally {
      captureHandler.close();
    }
  }
Example #6
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());
   }
 }
Example #7
0
 @Override
 public void publish(LogRecord record) {
   Object[] param = record.getParameters();
   if (param == null) {
     return;
   }
   if (msg != null && !msg.equals(record.getMessage())) {
     return;
   }
   cnt++;
   for (Object o : param) {
     instances.put(o, record.getMessage());
   }
 }
Example #8
0
 @Override
 public void publish(final LogRecord record) {
   if (record.getLevel().intValue() < this.getLevel().intValue()
       || record.getLoggerName().equals(getClass().getName())) {
     return;
   }
   try {
     Mailer.instance()
         .send(
             (message) -> {
               message.addRecipient(
                   Message.RecipientType.TO,
                   new InternetAddress(
                       "clash.nanobot+log."
                           + record.getLevel().getName().toLowerCase()
                           + "@gmail.com"));
               message.setSubject(record.getLevel() + ": " + record.getMessage());
               String emailBody = "<table border=\"1\" cellspacing=\"0\" cellpadding=\"3\">";
               emailBody +=
                   "<tr><td>Version</td><td>" + BuildInfo.instance().getVersion() + "</td></tr>";
               emailBody +=
                   "<tr><td>BuildTime</td><td>"
                       + BuildInfo.instance().getTimestamp()
                       + "</td></tr>";
               emailBody += "<tr><td>Time</td><td>" + record.getMillis() + "</td></tr>";
               emailBody += "<tr><td>Thread</td><td>" + record.getThreadID() + "</td></tr>";
               emailBody += "<tr><td>Logger</td><td>" + record.getLoggerName() + "</td></tr>";
               emailBody += "<tr><td>Class</td><td>" + record.getSourceClassName() + "</td></tr>";
               emailBody +=
                   "<tr><td>Method</td><td>" + record.getSourceMethodName() + "</td></tr>";
               emailBody += "<tr><td>Level</td><td>" + record.getLevel() + "</td></tr>";
               emailBody += "<tr><td>Message</td><td>" + record.getMessage() + "</td></tr>";
               final Throwable e = record.getThrown();
               if (e != null) {
                 final StringWriter writer = new StringWriter();
                 e.printStackTrace(new PrintWriter(writer));
                 emailBody +=
                     "<tr><td>Exception</td><td>"
                         + writer.toString().replace("\n", "<br/>")
                         + "</td></tr>";
               }
               emailBody += "</table>";
               message.setContent(emailBody, "text/html");
             });
   } catch (final Exception e) {
     logger.log(Level.SEVERE, e.getMessage(), e);
   }
 }
 @Override
 public String format(LogRecord record) {
   StringBuilder sb = new StringBuilder();
   sb.append(record.getMessage());
   sb.append('\n');
   return sb.toString();
 }
  @Test
  public void testGetFilterChain() throws Exception {
    mockBundleWiring();

    CaptureHandler captureHandler =
        JDKLoggerTestUtil.configureJDKLogger(MockLoggingFilter.class.getName(), Level.INFO);

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

      String cssFilterName = "CSS Filter";

      registerFilter(cssFilterName, new MockLoggingFilter(cssFilterName), null, "/css/*");

      String jsFilterName = "JS Filter";

      registerFilter(jsFilterName, new MockLoggingFilter(jsFilterName), null, "/js/*");

      FilterChain filterChain = _bundleServletContext.getFilterChain("/js/main.js");

      Assert.assertNotNull(filterChain);

      filterChain.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse());

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

      LogRecord logRecord = logRecords.get(0);

      Assert.assertEquals(jsFilterName, logRecord.getMessage());

      verifyBundleWiring();
    } finally {
      captureHandler.close();
    }
  }
  /*
   * (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 List<String> messages() {
   List<String> result = new ArrayList<String>();
   for (LogRecord record : records) {
     result.add(record.getMessage());
   }
   return result;
 }
Example #13
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();
  }
  private void validateNullableWarns(Injector injector, Dependency<?> dependency) {
    final List<LogRecord> logRecords = Lists.newArrayList();
    final Handler fakeHandler =
        new Handler() {
          @Override
          public void publish(LogRecord logRecord) {
            logRecords.add(logRecord);
          }

          @Override
          public void flush() {}

          @Override
          public void close() throws SecurityException {}
        };
    Logger.getLogger(Guice.class.getName()).addHandler(fakeHandler);
    try {
      injector.getInstance(Integer.class); // no exception, but assert it does log.
      LogRecord record = Iterables.getOnlyElement(logRecords);
      assertEquals(
          "Guice injected null into {0} (a {1}), please mark it @Nullable."
              + " Use -Dguice_check_nullable_provides_params=ERROR to turn this into an"
              + " error.",
          record.getMessage());
      assertEquals(Errors.convert(dependency.getKey()), record.getParameters()[1]);
    } finally {
      Logger.getLogger(Guice.class.getName()).removeHandler(fakeHandler);
    }
  }
 public String format(LogRecord record) {
   Object[] arguments = new Object[3];
   arguments[0] = record.getLoggerName();
   arguments[1] = record.getLevel();
   arguments[2] = record.getMessage();
   return messageFormat.format(arguments);
 }
Example #16
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();
  }
Example #17
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));
  }
Example #18
0
  /**
   * (non-Javadoc)
   *
   * @see java.util.logging.Handler#publish(java.util.logging.LogRecord)
   */
  public void publish(LogRecord record) {

    System.out.println("==============");
    System.out.println("GLOBAL LOGGER:");
    System.out.println("==============");
    System.out.println("" + record.getMessage());
    System.out.println("");
  }
Example #19
0
 @Override
 public void publish(LogRecord record) {
   if (!handlerClosed) {
     logTextArea.append(record.getMessage() + "\n");
     logTextArea.setCaretPosition(logTextArea.getDocument().getLength() - 1);
     logTextArea.repaint();
   }
 }
Example #20
0
  /**
   * Returns the record messages as a List<String>
   *
   * @return the record messages as a List<String>
   */
  public List<String> getMessages() {
    List<String> messages = new ArrayList<>();

    for (LogRecord r : records) {
      messages.add(r.getMessage());
    }

    return messages;
  }
    public void publish(LogRecord r) {
      String s = r.getMessage();

      if (s.startsWith("Resolvers computed")) {
        switchDone = true;
        Lkp lkp = (Lkp) org.openide.util.Lookup.getDefault();
        lkp.turn(Lkp.c2);
      }
    }
Example #22
0
  @Override
  public String format(LogRecord record) {

    StringBuilder sb = new StringBuilder();
    sb.append("[" + record.getLevel() + "] - ");
    sb.append(new Date(record.getMillis()) + " : ");
    sb.append(record.getSourceClassName() + "." + record.getSourceMethodName() + " : ");
    sb.append(record.getMessage() + "\n");
    return sb.toString();
  }
Example #23
0
 @Override
 public String format(LogRecord record) {
   return String.format(
       "[%1$tF %1$tT %5$s] %2$s [%3$s/%4$s]\n",
       new Date(record.getMillis()),
       record.getMessage(),
       record.getSourceClassName(),
       record.getSourceMethodName(),
       record.getLevel().getName());
 }
 @Override
 public String format(LogRecord record) {
   return "["
       + this.dateFormat.format(new Date(record.getMillis()))
       + "]["
       + record.getLevel().toString()
       + "] "
       + record.getMessage()
       + "\n";
 }
  @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());
    }
  }
 public String format(LogRecord rec) {
   StringBuffer buf = new StringBuffer(1000);
   buf.append(rec.getLevel());
   buf.append(" ");
   buf.append(calcDate(rec.getMillis()));
   buf.append(' ');
   buf.append(rec.getMessage());
   buf.append('\n');
   return buf.toString();
 }
Example #27
0
 // inefficient implementation
 public String format(final LogRecord record) {
   return record.getMillis()
       + " "
       + record.getLevel()
       + " ["
       + record.getSourceClassName()
       + "] "
       + record.getMessage()
       + "\n";
 }
Example #28
0
 @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));
 }
  @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(record.getMessage());
    }
    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();
  }
Example #30
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;
 }