Example #1
1
  /**
   * This method differentiates RollingFileAppender from its super class.
   *
   * @since 0.9.0
   */
  @Override
  protected void subAppend(LoggingEvent event) {
    if (id == null) {
      id = "" + new Random().nextInt();
      this.qw.write("#Session:" + id + ";" + Calendar.getInstance().getTime());
      this.qw.write(Layout.LINE_SEP);
    }
    this.qw.write(id);
    this.qw.write("#");
    this.qw.write(this.layout.format(event));
    if (layout.ignoresThrowable()) {
      String[] s = event.getThrowableStrRep();
      if (s != null) {
        Thread.dumpStack();
        int len = s.length;
        for (int i = 0; i < len; i++) {
          this.qw.write(id + "#[" + event.getThreadName() + "] " + event.getLevel() + " - \t");
          this.qw.write(s[i]);
          this.qw.write(Layout.LINE_SEP);
        }
      }
    }

    if (this.immediateFlush) {
      this.qw.flush();
    }
    if (fileName != null && ((CountingQuietWriter) qw).getCount() >= maxFileSize) {
      this.rollOver();
    }
  }
  @Test
  public void testObsoletePortalKeys() throws Exception {
    String[] originalObsoletePortalKeys =
        ReflectionTestUtil.getFieldValue(VerifyProperties.class, "_OBSOLETE_PORTAL_KEYS");

    String obsoletePortalKey = getFirstPortalPropertyKey();

    ReflectionTestUtil.setFieldValue(
        VerifyProperties.class, "_OBSOLETE_PORTAL_KEYS", new String[] {obsoletePortalKey});

    try (CaptureAppender captureAppender =
        Log4JLoggerTestUtil.configureLog4JLogger(VerifyProperties.class.getName(), Level.ERROR)) {

      doVerify();

      List<LoggingEvent> loggingEvents = captureAppender.getLoggingEvents();

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

      LoggingEvent loggingEvent = loggingEvents.get(0);

      Assert.assertEquals(
          "Portal property \"" + obsoletePortalKey + "\" is obsolete", loggingEvent.getMessage());
    } finally {
      ReflectionTestUtil.setFieldValue(
          VerifyProperties.class, "_OBSOLETE_PORTAL_KEYS", originalObsoletePortalKeys);
    }
  }
  @Test
  public void testRenamedSystemKeys() throws Exception {
    String[][] originalRenamedSystemKeys =
        ReflectionTestUtil.getFieldValue(VerifyProperties.class, "_RENAMED_SYSTEM_KEYS");

    String renamedSystemKey = getFirstSystemPropertyKey();

    ReflectionTestUtil.setFieldValue(
        VerifyProperties.class,
        "_RENAMED_SYSTEM_KEYS",
        new String[][] {new String[] {renamedSystemKey, renamedSystemKey}});

    try (CaptureAppender captureAppender =
        Log4JLoggerTestUtil.configureLog4JLogger(VerifyProperties.class.getName(), Level.ERROR)) {

      doVerify();

      List<LoggingEvent> loggingEvents = captureAppender.getLoggingEvents();

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

      LoggingEvent loggingEvent = loggingEvents.get(0);

      Assert.assertEquals(
          "System property \""
              + renamedSystemKey
              + "\" was renamed to \""
              + renamedSystemKey
              + "\"",
          loggingEvent.getMessage());
    } finally {
      ReflectionTestUtil.setFieldValue(
          VerifyProperties.class, "_RENAMED_SYSTEM_KEYS", originalRenamedSystemKeys);
    }
  }
  @Test
  public void testMigratedPortalKeys() throws Exception {
    String[][] originalMigratedPortalKeys =
        ReflectionTestUtil.getFieldValue(VerifyProperties.class, "_MIGRATED_PORTAL_KEYS");

    String migratedPortalKey = getFirstPortalPropertyKey();

    ReflectionTestUtil.setFieldValue(
        VerifyProperties.class,
        "_MIGRATED_PORTAL_KEYS",
        new String[][] {new String[] {migratedPortalKey, migratedPortalKey}});

    try (CaptureAppender captureAppender =
        Log4JLoggerTestUtil.configureLog4JLogger(VerifyProperties.class.getName(), Level.ERROR)) {

      doVerify();

      List<LoggingEvent> loggingEvents = captureAppender.getLoggingEvents();

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

      LoggingEvent loggingEvent = loggingEvents.get(0);

      Assert.assertEquals(
          "Portal property \""
              + migratedPortalKey
              + "\" was migrated to the system property \""
              + migratedPortalKey
              + "\"",
          loggingEvent.getMessage());
    } finally {
      ReflectionTestUtil.setFieldValue(
          VerifyProperties.class, "_MIGRATED_PORTAL_KEYS", originalMigratedPortalKeys);
    }
  }
Example #5
0
  @Override
  protected void append(LoggingEvent logEvent) {
    final String message = logEvent.getRenderedMessage();
    final Level level = logEvent.getLevel();
    final String streamId = getStreamId(level);

    final Display display = Display.getDefault();
    final Thread thread = display.getThread();
    Thread _currentThread = Thread.currentThread();
    final boolean uiThread = Objects.equal(thread, _currentThread);
    final Runnable _function =
        new Runnable() {
          @Override
          public void run() {
            try {
              final IOConsole console = AntlrConsoleFactory.getConsole();
              final IOConsoleOutputStream stream = console.newOutputStream();
              final ConsoleColorProvider colorProvider = new ConsoleColorProvider();
              final Color color = colorProvider.getColor(streamId);
              stream.setColor(color);
              stream.setActivateOnWrite(true);
              stream.write((message + "\n"));
              stream.close();
            } catch (Throwable ex) {
              ex.printStackTrace();
            }
          }
        };
    final Runnable printTask = _function;
    if (uiThread) {
      printTask.run();
    } else {
      display.syncExec(printTask);
    }
  }
Example #6
0
  /*
   * (non-Javadoc)
   *
   * @see org.apache.log4j.AppenderSkeleton#append(org.apache.log4j.spi.LoggingEvent)
   */
  @Override
  protected void append(LoggingEvent event) {
    final Level l = event.getLevel();
    final String message = (event.getMessage() != null ? event.getMessage().toString() : "");

    Throwable throwable = null;
    if (event.getThrowableInformation() != null) {
      throwable = event.getThrowableInformation().getThrowable();
    }

    switch (l.toInt()) {
      case Priority.OFF_INT:
        // Logging turned off - do nothing.
        break;

      case Priority.FATAL_INT:
      case Priority.ERROR_INT:
        Log.error(message, throwable);
        break;

      case Priority.WARN_INT:
        Log.warn(message, throwable);
        break;

      case Priority.INFO_INT:
        Log.info(message, throwable);
        break;

      default:
        // DEBUG and below (trace, all)
        Log.debug(message, throwable);
        break;
    }
  }
 public String convert(LoggingEvent event) {
   if (key == null) {
     StringBuffer buf = new StringBuffer("{");
     Map properties = event.getProperties();
     if (properties.size() > 0) {
       Object[] keys = properties.keySet().toArray();
       Arrays.sort(keys);
       for (int i = 0; i < keys.length; i++) {
         buf.append('{');
         buf.append(keys[i]);
         buf.append(',');
         buf.append(properties.get(keys[i]));
         buf.append('}');
       }
     }
     buf.append('}');
     return buf.toString();
   } else {
     Object val = event.getMDC(key);
     if (val == null) {
       return null;
     } else {
       return val.toString();
     }
   }
 }
  @Test
  public void appenderStoresMessages() {
    MemoryAppender appender = new MemoryAppender();
    BasicConfigurator.configure(appender);

    Logger logger = Logger.getLogger(TEST_CATEGORY);
    logger.setLevel(Level.ERROR);

    logger.error(TEST_MESSAGE);

    LinkedList<LoggingEvent> events = appender.getEvents();
    assertEquals(1, events.size());

    LoggingEvent event = events.getFirst();
    assertEquals(Level.ERROR, event.getLevel());
    assertEquals(TEST_CATEGORY, event.getLoggerName());
    assertEquals(TEST_MESSAGE, event.getMessage());
    assertEquals(TEST_LOCATION, event.getLocationInformation().getClassName());

    appender.clear();
    assertEquals(0, events.size());

    logger.error(TEST_MESSAGE);
    assertEquals(1, appender.getEvents().size());
  }
  @Test
  public void testFailedPortletLocalPublishing() throws Exception {
    User user = TestPropsValues.getUser();

    try (CaptureAppender captureAppender =
        Log4JLoggerTestUtil.configureLog4JLogger(
            BackgroundTaskMessageListener.class.getName(), Level.ERROR)) {

      StagingUtil.publishPortlet(
          user.getUserId(),
          _group.getGroupId(),
          _liveGroup.getGroupId(),
          0,
          0,
          StringPool.BLANK,
          _parameterMap);

      List<LoggingEvent> loggingEvents = captureAppender.getLoggingEvents();

      LoggingEvent loggingEvent = loggingEvents.get(0);

      Assert.assertEquals("Unable to execute background task", loggingEvent.getMessage());

      ThrowableInformation throwableInformation = loggingEvent.getThrowableInformation();

      Throwable throwable = throwableInformation.getThrowable();

      Assert.assertSame(NoSuchLayoutException.class, throwable.getClass());
    }

    Assert.assertTrue(
        _firedExportImportLifecycleEventsMap.containsKey(
            ExportImportLifecycleConstants.EVENT_PUBLICATION_PORTLET_LOCAL_FAILED));
  }
Example #10
0
 private String resolveFilename(LoggingEvent event) {
   String loggerName = event.getLoggerName();
   String result = getCustomLogFullFileName(loggerName);
   if (result == null) {
     result = getDefaultLogFullFileName(event.getLevel());
   }
   return result;
 }
 @Override
 protected void append(LoggingEvent event) {
   Throwable throwable = null;
   ThrowableInformation throwableInfo = event.getThrowableInformation();
   if (throwableInfo != null) {
     throwable = throwableInfo.getThrowable();
   }
   fireApplicationEvent(event.getLevel(), asString(event), throwable);
 }
Example #12
0
 private LogMessageEntity convertToLogMessageEntity(LoggingEvent loggingEvent)
     throws UnknownHostException {
   return new LogMessageEntity(
       loggingEvent.getTimeStamp(),
       loggingEvent.getRenderedMessage(),
       new PatternLayout("%C{1}").format(loggingEvent),
       (String) loggingEvent.getMDC(MDCHelper.MDC_TRANSACTION_ID),
       String.format("%s / %s", nodeId, InetAddress.getLocalHost().getHostName()));
 }
Example #13
0
 /* 245:    */
 /* 246:    */ public void append(LoggingEvent event) /* 247:    */ {
   /* 248:298 */ if (!isAsSevereAsThreshold(event.getLevel())) {
     /* 249:299 */ return;
     /* 250:    */ }
   /* 251:302 */ if (this.sqw == null)
   /* 252:    */ {
     /* 253:303 */ this.errorHandler.error(
         "No syslog host is set for SyslogAppedender named \"" + this.name + "\".");
     /* 254:    */
     /* 255:305 */ return;
     /* 256:    */ }
   /* 257:308 */ if (!this.layoutHeaderChecked)
   /* 258:    */ {
     /* 259:309 */ if ((this.layout != null) && (this.layout.getHeader() != null)) {
       /* 260:310 */ sendLayoutMessage(this.layout.getHeader());
       /* 261:    */ }
     /* 262:312 */ this.layoutHeaderChecked = true;
     /* 263:    */ }
   /* 264:315 */ String hdr = getPacketHeader(event.timeStamp);
   /* 265:    */ String packet;
   /* 266:    */ String packet;
   /* 267:317 */ if (this.layout == null) {
     /* 268:318 */ packet = String.valueOf(event.getMessage());
     /* 269:    */ } else {
     /* 270:320 */ packet = this.layout.format(event);
     /* 271:    */ }
   /* 272:322 */ if ((this.facilityPrinting) || (hdr.length() > 0))
   /* 273:    */ {
     /* 274:323 */ StringBuffer buf = new StringBuffer(hdr);
     /* 275:324 */ if (this.facilityPrinting) {
       /* 276:325 */ buf.append(this.facilityStr);
       /* 277:    */ }
     /* 278:327 */ buf.append(packet);
     /* 279:328 */ packet = buf.toString();
     /* 280:    */ }
   /* 281:331 */ this.sqw.setLevel(event.getLevel().getSyslogEquivalent());
   /* 282:335 */ if (packet.length() > 256) {
     /* 283:336 */ splitPacket(hdr, packet);
     /* 284:    */ } else {
     /* 285:338 */ this.sqw.write(packet);
     /* 286:    */ }
   /* 287:341 */ if ((this.layout == null) || (this.layout.ignoresThrowable()))
   /* 288:    */ {
     /* 289:342 */ String[] s = event.getThrowableStrRep();
     /* 290:343 */ if (s != null) {
       /* 291:344 */ for (int i = 0; i < s.length; i++) {
         /* 292:345 */ if (s[i].startsWith("\t")) {
           /* 293:346 */ this.sqw.write(hdr + "    " + s[i].substring(1));
           /* 294:    */ } else {
           /* 295:348 */ this.sqw.write(hdr + s[i]);
           /* 296:    */ }
         /* 297:    */ }
       /* 298:    */ }
     /* 299:    */ }
   /* 300:    */ }
 public List<LoggingEvent> grep(org.apache.log4j.Level level, String message) {
   List<LoggingEvent> result = new ArrayList<>();
   for (LoggingEvent event : events) {
     if (event.getLevel() == level
         && event.getMessage() != null
         && message != null
         && event.getMessage().toString().matches(message)) {
       result.add(event);
     }
   }
   return result;
 }
  /**
   * Encodes a LoggingEvent into a HashMap using the logstash JSON format.
   *
   * @param loggingEvent The LoggingEvent to encode.
   * @param includeLocationInfo Whether to include LocationInfo in the map, or not.
   * @return A Map representing the LoggingEvent, which is suitable to be serialized by a JSON
   *     encoder such as Jackson.
   */
  @SuppressWarnings("rawtypes")
  public static Map<String, Object> encodeToMap(
      LoggingEvent loggingEvent, boolean includeLocationInfo) {
    Map<String, Object> logstashEvent = new LoggingEventMap();
    String threadName = loggingEvent.getThreadName();
    long timestamp = loggingEvent.getTimeStamp();
    HashMap<String, Object> exceptionInformation = new HashMap<String, Object>();
    Map mdc = loggingEvent.getProperties();
    String ndc = loggingEvent.getNDC();

    logstashEvent.put("@version", VERSION);
    logstashEvent.put("@timestamp", dateFormat(timestamp));
    logstashEvent.put("source_host", getHostname());
    logstashEvent.put("message", loggingEvent.getRenderedMessage());

    if (loggingEvent.getThrowableInformation() != null) {
      final ThrowableInformation throwableInformation = loggingEvent.getThrowableInformation();
      if (throwableInformation.getThrowable().getClass().getCanonicalName() != null) {
        exceptionInformation.put(
            "exception_class", throwableInformation.getThrowable().getClass().getCanonicalName());
      }
      if (throwableInformation.getThrowable().getMessage() != null) {
        exceptionInformation.put(
            "exception_message", throwableInformation.getThrowable().getMessage());
      }
      if (throwableInformation.getThrowableStrRep() != null) {
        StringBuilder stackTrace = new StringBuilder();
        for (String line : throwableInformation.getThrowableStrRep()) {
          stackTrace.append(line);
          stackTrace.append("\n");
        }
        exceptionInformation.put("stacktrace", stackTrace);
      }
      logstashEvent.put("exception", exceptionInformation);
    }

    if (includeLocationInfo) {
      LocationInfo info = loggingEvent.getLocationInformation();
      logstashEvent.put("file", info.getFileName());
      logstashEvent.put("line_number", info.getLineNumber());
      logstashEvent.put("class", info.getClassName());
      logstashEvent.put("method", info.getMethodName());
    }

    logstashEvent.put("logger_name", loggingEvent.getLoggerName());
    logstashEvent.put("mdc", mdc);
    logstashEvent.put("ndc", ndc);
    logstashEvent.put("level", loggingEvent.getLevel().toString());
    logstashEvent.put("thread_name", threadName);

    return logstashEvent;
  }
  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());
  }
 @Override
 public String format(LoggingEvent event) {
   String newMsg = StringEscapeUtils.escapeHtml4(event.getMessage().toString());
   LoggingEvent encodedEvent =
       new LoggingEvent(
           event.fqnOfCategoryClass,
           event.getLogger(),
           event.timeStamp,
           event.level,
           newMsg,
           event.getThrowableInformation().getThrowable());
   String baseFmt = super.format(encodedEvent).replace("@{{", "<").replace("@}}", ">");
   return "<div class=step${event.level.toString()}>${baseFmt}</div><br/>";
 }
 @Override
 public void match(LoggingEvent event) {
   if (event.getLevel() == level && event.getLoggerName().equals(logger)) {
     if (Regex.isSimpleMatchPattern(message)) {
       if (Regex.simpleMatch(message, event.getMessage().toString())) {
         saw = true;
       }
     } else {
       if (event.getMessage().toString().contains(message)) {
         saw = true;
       }
     }
   }
 }
 /*     */ public String convert(LoggingEvent event) /*     */ {
   /* 393 */ switch (this.type) {
       /*     */ case 2000:
       /* 395 */ return Long.toString(event.timeStamp - LoggingEvent.getStartTime());
       /*     */ case 2001:
       /* 397 */ return event.getThreadName();
       /*     */ case 2002:
       /* 399 */ return event.getLevel().toString();
       /*     */ case 2003:
       /* 401 */ return event.getNDC();
       /*     */ case 2004:
       /* 403 */ return event.getRenderedMessage();
       /*     */ }
   /* 405 */ return null;
   /*     */ }
Example #20
0
 /** {@inheritDoc} */
 public void doAppend(final LoggingEvent event) {
   final String message = event.getMessage().toString();
   if (!message.startsWith(TEST_PREFIX)) {
     return;
   }
   messages.add(message);
 }
Example #21
0
 /**
  * @param event
  * @param depth
  * @param lfc
  * @param ndcStr
  */
 private void start(LoggingEvent event, int depth, TimelineLifecycle lfc, String ndcStr) {
   NdcContext ndcCtxt = getNdcContext(lfc);
   if (ndcCtxt.getNdcObj() != null)
     throw new IllegalStateException(
         "ZMonitor Log4j stack Operation Logic Error or forget to cleanup the state.");
   ndcCtxt.doStart(createName(event, null), event.getRenderedMessage(), ndcStr, depth);
 }
Example #22
0
 /** @see org.apache.log4j.spi.Filter#decide(org.apache.log4j.spi.LoggingEvent) */
 @Override
 public int decide(LoggingEvent event) {
   if (nestedDiagnosticContext.equals(event.getNDC())) {
     return ACCEPT;
   }
   return DENY;
 }
 /*     */ public String convert(LoggingEvent event) /*     */ {
   /* 463 */ Object val = event.getMDC(this.key);
   /* 464 */ if (val == null) {
     /* 465 */ return null;
     /*     */ }
   /* 467 */ return val.toString();
   /*     */ }
  public String format(LoggingEvent loggingEvent) {

    StringBuffer oBuffer = new StringBuffer();
    switch (loggingEvent.getLevel().toInt()) {
      case Level.ALL_INT:
        oBuffer.append(all);
        break;
      case Level.FATAL_INT:
        oBuffer.append(fatal);
        break;
      case Level.ERROR_INT:
        oBuffer.append(error);
        break;
      case Level.WARN_INT:
        oBuffer.append(warn);
        break;
      case Level.INFO_INT:
        oBuffer.append(info);
        break;
      case Level.DEBUG_INT:
        oBuffer.append(debug);
        break;
    }
    oBuffer.append(super.format(loggingEvent));
    oBuffer.append(defaultcolor);
    return oBuffer.toString();
  }
Example #25
0
 private void opt(String key, StringBuffer buf, LoggingEvent event) {
   Object val = event.getMDC(key);
   if (val != null) {
     buf.append(' ');
     buf.append(val);
   }
 }
Example #26
0
  /**
   * This method performs threshold checks and invokes filters before delegating actual logging to
   * the subclasses specific {@link AppenderSkeleton#append} method.
   */
  public synchronized void doAppend(LoggingEvent event) {
    if (closed) {
      LogLog.error("Attempted to append to closed appender named [" + name + "].");
      return;
    }

    if (!isAsSevereAsThreshold(event.getLevel())) {
      return;
    }

    Filter f = this.headFilter;

    FILTER_LOOP:
    while (f != null) {
      switch (f.decide(event)) {
        case Filter.DENY:
          return;
        case Filter.ACCEPT:
          break FILTER_LOOP;
        case Filter.NEUTRAL:
          f = f.getNext();
      }
    }

    this.append(event);
  }
 public void process(LoggingEvent loggingEvent) {
   // we ignore events for SLF4J
   if (!ORG_SLF4J_IMPL_JCL_LOGGER_ADAPTER.equals(
       loggingEvent.getLocationInformation().getClassName())) {
     queue.offer(loggingEvent);
   }
 }
    public void doAppend(LoggingEvent arg0) {
      String logger = arg0.getLoggerName();
      String message = arg0.getRenderedMessage();
      Level level = arg0.getLevel();

      Set toIgnore = (Set) m_ignore.get(logger);
      if (toIgnore != null) {
        // if any of the strings in the set start our message, skip it
        for (Iterator i = toIgnore.iterator(); i.hasNext(); ) {
          String start = (String) i.next();
          if (message.startsWith(start)) return;
        }
      }

      m_other.doAppend(arg0);
    }
Example #29
0
 /**
  * @param event
  * @return
  */
 protected Name createName(LoggingEvent event, String name) {
   JavaName jName = new JavaName(name == null ? measurePointNameType : name);
   if (locationInfo) {
     LocationInfo locInfo = event.getLocationInformation();
     jName.setClassName(locInfo.getClassName());
     jName.setMethodName(locInfo.getMethodName());
     Integer lineNum = null;
     try {
       lineNum = Integer.parseInt(locInfo.getLineNumber());
     } catch (Exception e) {
     } // line number is not applicable, ignore it.
     if (lineNum != null) jName.setLineNumber(lineNum);
   } else {
     jName.setClassName(event.getLoggerName());
   }
   return jName;
 }
Example #30
0
 public void doAppend(LoggingEvent arg0) {
   String message = arg0.getMessage().toString();
   if (message.contains("START INBOUND")) startInbound++;
   else if (message.contains("END INBOUND")) endInbound++;
   else if (message.contains("START OUTBOUND")) startOutbound++;
   else if (message.contains("END OUTBOUND")) endOutbound++;
   messages.add(message.toString());
 }