Esempio n. 1
0
 public static void printAllMessages() {
   if (lastInstance == null) {
     System.out.println(
         "Unable to print out trace level root logger messages - please "
             + "configure MemoryAppender on the <root> logger in log4j - config.xml");
   } else {
     System.out.println(
         String.format(
             "Printing last %d of %d log messages", eventsList.size(), messageCount.get()));
     lastInstance.appendAll();
   }
 }
Esempio n. 2
0
  public static void assertMessagesLogged(
      Collection<String> expectedPatternsRO,
      Collection<String> unexpectedPatterns,
      String filterPattern,
      boolean verbose) {
    Set<String> encounteredPatterns = new TreeSet<>();
    List<String> encounteredUnexpectedMessages = new ArrayList<>();
    List<String> expectedPatterns = new ArrayList<>(expectedPatternsRO);
    Collection<String> unexpected =
        unexpectedPatterns == null ? Collections.emptyList() : unexpectedPatterns;

    for (LoggingEvent event : MemoryAppender.getEvents()) {
      String message = event.getMessage().toString();
      if (filterPattern == null || message.matches(filterPattern)) {
        if (verbose) {
          System.out.println(event.getLevel() + " " + message);
        }
        Iterator<String> iterator = expectedPatterns.iterator();
        while (iterator.hasNext()) {
          String pattern = iterator.next();
          if (message.matches(".*" + pattern + ".*")) {
            encounteredPatterns.add(pattern);
            iterator.remove();
          }
        }
        iterator = unexpected.iterator();
        while (iterator.hasNext()) {
          String pattern = iterator.next();
          if (message.matches(".*" + pattern + ".*")) {
            encounteredUnexpectedMessages.add(message);
          }
        }
      }
    }
    StringBuffer errorMessage = new StringBuffer();
    if (!encounteredUnexpectedMessages.isEmpty()) {
      errorMessage.append("\n- the following unexpected messages were encountered: ");
      for (String message : encounteredUnexpectedMessages) {
        errorMessage.append("\n  " + message);
      }
    }
    if (!expectedPatterns.isEmpty()) {
      errorMessage.append(
          "\n- the following patterns of log messages were not logged: "
              + expectedPatterns
              + (verbose ? ",\nonly these were logged: " + encounteredPatterns : ""));
    }
    assertTrue(
        "Log messages were not as expected" + errorMessage.toString(),
        expectedPatterns.isEmpty() && encounteredUnexpectedMessages.isEmpty());
  }