Ejemplo n.º 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();
    }
  }
Ejemplo n.º 2
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:    */ }
  @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());
  }
Ejemplo n.º 4
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);
    }
  }
Ejemplo n.º 5
0
 /**
  * Convert logging event to map
  *
  * @param e
  * @return
  */
 public static Map<String, Object> toMap(LoggingEvent e) {
   final Map<String, Object> m =
       Objects.newHashMap(
           "name", e.getLoggerName(),
           "date", new Date(e.getTimeStamp()),
           "level", e.getLevel().toString(),
           "thread", e.getThreadName(),
           "message", "" + e.getMessage(),
           "fileName", e.getLocationInformation().getFileName(),
           "methodName", e.getLocationInformation().getMethodName(),
           "lineNumber", e.getLocationInformation().getLineNumber(),
           "requestId", e.getMDC("requestId"),
           "sessionId", e.getMDC("sessionId"),
           "freeMemory", Runtime.getRuntime().freeMemory(),
           "throwable", null);
   if (e.getThrowableInformation() != null && e.getThrowableInformation().getThrowable() != null) {
     Throwable t = e.getThrowableInformation().getThrowable();
     m.put(
         "throwable",
         Objects.newHashMap(
             "message", t.getMessage(),
             "class", t.getClass().getName(),
             "stackTrace", getStackTrace(t)));
   }
   return m;
 }
Ejemplo n.º 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 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();
  }
Ejemplo n.º 8
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);
  }
Ejemplo n.º 9
0
  @Override
  public String format(LoggingEvent event) {
    if (sbuf.capacity() > MAX_CAPACITY) {
      sbuf = new StringBuffer(BUF_SIZE);
    } else {
      sbuf.setLength(0);
    }

    sbuf.append(Layout.LINE_SEP + "<tr>" + Layout.LINE_SEP);

    sbuf.append("<td title=\"Level\">");
    if (event.getLevel().equals(Level.DEBUG)) {
      sbuf.append("<font color=\"#339933\">");
      sbuf.append(Transform.escapeTags(String.valueOf(event.getLevel())));
      sbuf.append("</font>");
    } else if (event.getLevel().isGreaterOrEqual(Level.WARN)) {
      sbuf.append("<font color=\"#993300\"><strong>");
      sbuf.append(Transform.escapeTags(String.valueOf(event.getLevel())));
      sbuf.append("</strong></font>");
    } else {
      sbuf.append(Transform.escapeTags(String.valueOf(event.getLevel())));
    }
    sbuf.append("</td>" + Layout.LINE_SEP);

    sbuf.append("<td title=\"Message\">");
    sbuf.append(Transform.escapeTags(event.getRenderedMessage()));
    sbuf.append("</td>" + Layout.LINE_SEP);
    sbuf.append("</tr>" + Layout.LINE_SEP);

    if (event.getNDC() != null) {
      sbuf.append(
          "<tr><td bgcolor=\"#EEEEEE\" style=\"font-size : xx-small;\" colspan=\"6\" title=\"Nested Diagnostic Context\">");
      sbuf.append("NDC: " + Transform.escapeTags(event.getNDC()));
      sbuf.append("</td></tr>" + Layout.LINE_SEP);
    }

    String[] s = event.getThrowableStrRep();
    if (s != null) {
      sbuf.append(
          "<tr><td bgcolor=\"#993300\" style=\"color:White; font-size : xx-small;\" colspan=\"6\">");
      appendThrowableAsHTML(s, sbuf);
      sbuf.append("</td></tr>" + Layout.LINE_SEP);
    }

    return sbuf.toString();
  }
Ejemplo n.º 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);
 }
 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;
 }
Ejemplo n.º 13
0
  /**
   * 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;
  }
Ejemplo n.º 14
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());
  }
Ejemplo n.º 15
0
 private void writeHeader(LoggingEvent event) {
   writePRI(event.getLevel());
   writeVersion();
   writeSP();
   writeTimeStamp(event.timeStamp);
   writeSP();
   writeString(hostName);
   writeSP();
   writeString(applicationName);
   writeSP();
   writeString(processID);
   writeSP();
   writeString(messageID);
 }
Ejemplo n.º 16
0
 @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;
       }
     }
   }
 }
Ejemplo n.º 17
0
  /**
   * Creates a new <code>EventDetails</code> instance.
   *
   * @param aEvent a <code>LoggingEvent</code> value
   */
  EventDetails(LoggingEvent aEvent) {

    this(
        aEvent.timeStamp,
        aEvent.getLevel(),
        aEvent.getLoggerName(),
        aEvent.getNDC(),
        aEvent.getThreadName(),
        aEvent.getRenderedMessage(),
        aEvent.getThrowableStrRep(),
        (aEvent.getLocationInformation() == null)
            ? null
            : aEvent.getLocationInformation().fullInfo);
  }
 /*     */ 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;
   /*     */ }
Ejemplo n.º 19
0
    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);
    }
Ejemplo n.º 20
0
 public String convert(LoggingEvent event) {
   switch (type) {
     case RELATIVE_TIME_CONVERTER:
       return (String.valueOf(event.timeStamp - LoggingEvent.getStartTime()));
     case THREAD_CONVERTER:
       return event.getThreadName();
     case LEVEL_CONVERTER:
       return event.getLevel().toString();
     case NDC_CONVERTER:
       return event.getNDC();
     case MESSAGE_CONVERTER:
       {
         return event.getRenderedMessage();
       }
     default:
       return null;
   }
 }
 private TextMessage createEventMessage(LoggingEvent event, String service, String environment)
     throws JMSException {
   TextMessage message = createMessage(this.layout.format(event));
   message.setStringProperty(Constants.LEVEL, event.getLevel().toString());
   message.setLongProperty(Constants.TIME_STAMP, event.getTimeStamp());
   message.setStringProperty(
       Constants.EXCEPTION, StringUtils.join(event.getThrowableStrRep(), "\n"));
   message.setStringProperty(Constants.SERVICE, service);
   message.setStringProperty(Constants.ENVIRONMENT, environment);
   @SuppressWarnings("unchecked")
   Map<String, Object> context = MDC.getContext();
   if (context != null) {
     for (String key : context.keySet()) {
       message.setStringProperty("context." + key, MDC.get(key).toString());
     }
   }
   return message;
 }
Ejemplo n.º 22
0
  @SuppressWarnings("unchecked")
  @Override
  protected void append(LoggingEvent event) {

    StringBuilder sb = this.stringBuilder.getSB();
    sb.setLength(0);

    ISO8601.format(new java.util.Date(), sb).append(fieldDelim);
    sb.append(event.getLevel()).append(fieldDelim).append(event.getLoggerName());

    Object obj = event.getMessage();

    // time UTC^]Level^]Map
    if (obj instanceof Map) {
      Map map = (Map) event.getMessage();
      Iterator it = map.keySet().iterator();
      Object key = null;
      while (it.hasNext()) {
        key = it.next();
        sb.append(fieldDelim).append(key.toString()).append(fieldEqual).append(map.get(key));
      }
    } else {
      // time UTC^]Level^]String
      sb.append(fieldDelim).append(obj.toString());
    }

    // Extract exceptions
    String[] s = event.getThrowableStrRep();
    if (s != null) {
      sb.append(fieldDelim).append("Exception").append(fieldEqual);
      int len = s.length;
      for (int i = 0; i < len; i++) {
        sb.append(s[i]).append("\n");
      }
    }
    consumer.process(sb.toString());
  }
Ejemplo n.º 23
0
    @Override
    public void run() {
      try {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        while (true) {
          final Event event = events.take();
          LoggingEvent logEvent = event.getEvent();

          String name = logEvent.getLogger().getName();
          Level level = logEvent.getLevel();

          MessageProperties amqpProps = new MessageProperties();
          amqpProps.setDeliveryMode(deliveryMode);
          amqpProps.setContentType(contentType);
          if (null != contentEncoding) {
            amqpProps.setContentEncoding(contentEncoding);
          }
          amqpProps.setHeader(CATEGORY_NAME, name);
          amqpProps.setHeader(CATEGORY_LEVEL, level.toString());
          if (generateId) {
            amqpProps.setMessageId(UUID.randomUUID().toString());
          }

          // Set applicationId, if we're using one
          if (null != applicationId) {
            amqpProps.setAppId(applicationId);
          }

          // Set timestamp
          Calendar tstamp = Calendar.getInstance();
          tstamp.setTimeInMillis(logEvent.getTimeStamp());
          amqpProps.setTimestamp(tstamp.getTime());

          // Copy properties in from MDC
          @SuppressWarnings("rawtypes")
          Map props = event.getProperties();
          @SuppressWarnings("unchecked")
          Set<Entry<?, ?>> entrySet = props.entrySet();
          for (Entry<?, ?> entry : entrySet) {
            amqpProps.setHeader(entry.getKey().toString(), entry.getValue());
          }
          LocationInfo locInfo = logEvent.getLocationInformation();
          if (!"?".equals(locInfo.getClassName())) {
            amqpProps.setHeader(
                "location",
                String.format(
                    "%s.%s()[%s]",
                    locInfo.getClassName(), locInfo.getMethodName(), locInfo.getLineNumber()));
          }

          StringBuilder msgBody;
          String routingKey;
          synchronized (layoutMutex) {
            msgBody = new StringBuilder(layout.format(logEvent));
            routingKey = routingKeyLayout.format(logEvent);
          }
          if (layout.ignoresThrowable() && null != logEvent.getThrowableInformation()) {
            ThrowableInformation tinfo = logEvent.getThrowableInformation();
            for (String line : tinfo.getThrowableStrRep()) {
              msgBody.append(String.format("%s%n", line));
            }
          }

          // Send a message
          try {
            Message message = null;
            if (AmqpAppender.this.charset != null) {
              try {
                message =
                    new Message(msgBody.toString().getBytes(AmqpAppender.this.charset), amqpProps);
              } catch (UnsupportedEncodingException e) {
                /* fall back to default */
              }
            }
            if (message == null) {
              message =
                  new Message(
                      msgBody.toString().getBytes(), amqpProps); // NOSONAR (default charset)
            }
            message = postProcessMessageBeforeSend(message, event);
            rabbitTemplate.send(exchangeName, routingKey, message);
          } catch (AmqpException e) {
            int retries = event.incrementRetries();
            if (retries < maxSenderRetries) {
              // Schedule a retry based on the number of times I've tried to re-send this
              retryTimer.schedule(
                  new TimerTask() {
                    @Override
                    public void run() {
                      events.add(event);
                    }
                  },
                  (long) (Math.pow(retries, Math.log(retries)) * 1000));
            } else {
              errorHandler.error(
                  "Could not send log message "
                      + logEvent.getRenderedMessage()
                      + " after "
                      + maxSenderRetries
                      + " retries",
                  e,
                  ErrorCode.WRITE_FAILURE,
                  logEvent);
            }
          }
        }
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
    }
Ejemplo n.º 24
0
  public String _format(LoggingEvent event) {
    String message = (String) event.getMessage();
    if (message == null) {
      message = "";
    }
    StringBuilder sb = new StringBuilder(message.length() + 80);

    long now = event.timeStamp;
    long timeFromStart = now - startTime;
    long timeSinceLast = now - lastTime;
    lastTime = now;
    String shortClassName =
        getShortClassName(
            event.getLocationInformation().getClassName(),
            event.getLocationInformation().getMethodName());

    /**
     * * sb.append(timeFromStart).append(' ').append(timeSinceLast); sb.append(' ');
     * sb.append(record.getSourceClassName()).append('.').append( record.getSourceMethodName());
     * sb.append(' '); sb.append(record.getLevel()); *
     */
    SolrRequestInfo requestInfo = SolrRequestInfo.getRequestInfo();
    SolrQueryRequest req = requestInfo == null ? null : requestInfo.getReq();
    SolrCore core = req == null ? null : req.getCore();
    ZkController zkController = null;
    CoreInfo info = null;

    if (core != null) {
      info = coreInfoMap.get(core.hashCode());
      if (info == null) {
        info = new CoreInfo();
        info.shortId = "C" + Integer.toString(CoreInfo.maxCoreNum++);
        coreInfoMap.put(core.hashCode(), info);

        if (sb.length() == 0) sb.append("ASYNC ");
        sb.append(" NEW_CORE " + info.shortId);
        sb.append(" name=" + core.getName());
        sb.append(" " + core);
      }

      zkController = core.getCoreDescriptor().getCoreContainer().getZkController();
      if (zkController != null) {
        if (info.url == null) {
          info.url = zkController.getBaseUrl() + "/" + core.getName();
          sb.append(" url=" + info.url + " node=" + zkController.getNodeName());
        }

        Map<String, Object> coreProps = getReplicaProps(zkController, core);
        if (info.coreProps == null || !coreProps.equals(info.coreProps)) {
          info.coreProps = coreProps;
          final String corePropsString =
              "coll:"
                  + core.getCoreDescriptor().getCloudDescriptor().getCollectionName()
                  + " core:"
                  + core.getName()
                  + " props:"
                  + coreProps;
          sb.append(" " + info.shortId + "_STATE=" + corePropsString);
        }
      }
    }

    if (sb.length() > 0) sb.append('\n');
    sb.append(timeFromStart);

    // sb.append("\nL").append(record.getSequenceNumber()); // log number is
    // useful for sequencing when looking at multiple parts of a log file, but
    // ms since start should be fine.
    appendThread(sb, event);

    appendMDC(sb);

    // todo: should be able to get port from core container for non zk tests

    if (info != null) {
      sb.append(' ').append(info.shortId); // core
    }

    if (shortClassName.length() > 0) {
      sb.append(' ').append(shortClassName);
    }

    if (event.getLevel() != Level.INFO) {
      sb.append(' ').append(event.getLevel());
    }

    sb.append(' ');
    appendMultiLineString(sb, message);
    ThrowableInformation thInfo = event.getThrowableInformation();
    if (thInfo != null) {
      Throwable th = event.getThrowableInformation().getThrowable();
      if (th != null) {
        sb.append(' ');
        String err = SolrException.toStr(th);
        String ignoredMsg = SolrException.doIgnore(th, err);
        if (ignoredMsg != null) {
          sb.append(ignoredMsg);
        } else {
          sb.append(err);
        }
      }
    }

    sb.append('\n');

    /**
     * * Isn't core specific... prob better logged from zkController if (info != null) {
     * ClusterState clusterState = zkController.getClusterState(); if (info.clusterState !=
     * clusterState) { // something has changed in the matrix... sb.append(zkController.getBaseUrl()
     * + " sees new ClusterState:"); } } *
     */
    return sb.toString();
  }
Ejemplo n.º 25
0
  public static final GelfMessage makeMessage(LoggingEvent event, GelfMessageProvider provider) {
    long timeStamp = Log4jVersionChecker.getTimeStamp(event);
    Level level = event.getLevel();

    String file = null;
    String lineNumber = null;
    if (provider.isIncludeLocation()) {
      LocationInfo locationInformation = event.getLocationInformation();
      file = locationInformation.getFileName();
      lineNumber = locationInformation.getLineNumber();
    }

    String renderedMessage = event.getRenderedMessage();
    String shortMessage;

    if (renderedMessage == null) {
      renderedMessage = "";
    }

    if (renderedMessage.length() > MAX_SHORT_MESSAGE_LENGTH) {
      shortMessage = renderedMessage.substring(0, MAX_SHORT_MESSAGE_LENGTH - 1);
    } else {
      shortMessage = renderedMessage;
    }

    if (provider.isExtractStacktrace()) {
      ThrowableInformation throwableInformation = event.getThrowableInformation();
      if (throwableInformation != null) {
        renderedMessage += "\n\r" + extractStacktrace(throwableInformation);
      }
    }

    GelfMessage gelfMessage =
        new GelfMessage(
            shortMessage,
            renderedMessage,
            timeStamp,
            String.valueOf(level.getSyslogEquivalent()),
            lineNumber,
            file);

    if (provider.getOriginHost() != null) {
      gelfMessage.setHost(provider.getOriginHost());
    }

    if (provider.getFacility() != null) {
      gelfMessage.setFacility(provider.getFacility());
    }

    Map<String, String> fields = provider.getFields();
    for (Map.Entry<String, String> entry : fields.entrySet()) {
      if (entry.getKey().equals(ORIGIN_HOST_KEY) && gelfMessage.getHost() == null) {
        gelfMessage.setHost(fields.get(ORIGIN_HOST_KEY));
      } else {
        gelfMessage.addField(entry.getKey(), entry.getValue());
      }
    }

    if (provider.isAddExtendedInformation()) {

      gelfMessage.addField(THREAD_NAME, event.getThreadName());
      gelfMessage.addField(LOGGER_NAME, event.getLoggerName());
      gelfMessage.addField(JAVA_TIMESTAMP, Long.toString(gelfMessage.getJavaTimestamp()));

      // Get MDC and add a GELF field for each key/value pair
      Map<String, Object> mdc = MDC.getContext();

      if (mdc != null) {
        for (Map.Entry<String, Object> entry : mdc.entrySet()) {

          gelfMessage.addField(entry.getKey(), entry.getValue().toString());
        }
      }

      // Get NDC and add a GELF field
      String ndc = event.getNDC();

      if (ndc != null) {

        gelfMessage.addField(LOGGER_NDC, ndc);
      }
    }

    return gelfMessage;
  }
Ejemplo n.º 26
0
 /**
  * Assert a <code>LoggingEvent</code> has the correct message and <code>org.apache.log4j.Level
  * </code>.
  */
 public static void assertLoggingEvent(
     org.apache.log4j.Level expectedLevel, String expectedMessage, LoggingEvent loggingEvent) {
   Assert.assertEquals(expectedLevel, loggingEvent.getLevel());
   Assert.assertEquals(expectedMessage, loggingEvent.getMessage());
 }
Ejemplo n.º 27
0
 void verifyWithLevelAndException(
     LoggingEvent le, XLogger.Level level, String expectedMsg, Throwable t) {
   verify(le, expectedMsg);
   assertEquals(t.toString(), le.getThrowableStrRep()[0]);
   assertEquals(le.getLevel().toString(), level.toString());
 }
Ejemplo n.º 28
0
  protected void append(LoggingEvent event) {
    Connection connection = null;
    try {
      connection = connectionSource.getConnection();
      connection.setAutoCommit(false);

      PreparedStatement insertStatement;
      if (cnxSupportsGetGeneratedKeys) {
        insertStatement = connection.prepareStatement(insertSQL, Statement.RETURN_GENERATED_KEYS);
      } else {
        insertStatement = connection.prepareStatement(insertSQL);
      }

      /*          insertStatement.setLong(1, event.getSequenceNumber());*/
      insertStatement.setLong(1, 0);

      insertStatement.setLong(2, event.getTimeStamp());
      insertStatement.setString(3, event.getRenderedMessage());
      insertStatement.setString(4, event.getLoggerName());
      insertStatement.setString(5, event.getLevel().toString());
      insertStatement.setString(6, event.getNDC());
      insertStatement.setString(7, event.getThreadName());
      insertStatement.setShort(8, DBHelper.computeReferenceMask(event));

      LocationInfo li;

      if (event.locationInformationExists() || locationInfo) {
        li = event.getLocationInformation();
      } else {
        li = LocationInfo.NA_LOCATION_INFO;
      }

      insertStatement.setString(9, li.getFileName());
      insertStatement.setString(10, li.getClassName());
      insertStatement.setString(11, li.getMethodName());
      insertStatement.setString(12, li.getLineNumber());

      int updateCount = insertStatement.executeUpdate();
      if (updateCount != 1) {
        LogLog.warn("Failed to insert loggingEvent");
      }

      ResultSet rs = null;
      Statement idStatement = null;
      boolean gotGeneratedKeys = false;
      if (cnxSupportsGetGeneratedKeys) {
        try {
          rs = (ResultSet) GET_GENERATED_KEYS_METHOD.invoke(insertStatement, null);
          gotGeneratedKeys = true;
        } catch (InvocationTargetException ex) {
          Throwable target = ex.getTargetException();
          if (target instanceof SQLException) {
            throw (SQLException) target;
          }
          throw ex;
        } catch (IllegalAccessException ex) {
          LogLog.warn("IllegalAccessException invoking PreparedStatement.getGeneratedKeys", ex);
        }
      }

      if (!gotGeneratedKeys) {
        insertStatement.close();
        insertStatement = null;

        idStatement = connection.createStatement();
        idStatement.setMaxRows(1);
        rs = idStatement.executeQuery(sqlDialect.getSelectInsertId());
      }

      // A ResultSet cursor is initially positioned before the first row; the
      // first call to the method next makes the first row the current row
      rs.next();
      int eventId = rs.getInt(1);

      rs.close();

      // we no longer need the insertStatement
      if (insertStatement != null) {
        insertStatement.close();
        insertStatement = null;
      }

      if (idStatement != null) {
        idStatement.close();
        idStatement = null;
      }

      Set propertiesKeys = event.getPropertyKeySet();

      if (propertiesKeys.size() > 0) {
        PreparedStatement insertPropertiesStatement =
            connection.prepareStatement(insertPropertiesSQL);

        for (Iterator i = propertiesKeys.iterator(); i.hasNext(); ) {
          String key = (String) i.next();
          String value = event.getProperty(key);

          // LogLog.info("id " + eventId + ", key " + key + ", value " + value);
          insertPropertiesStatement.setInt(1, eventId);
          insertPropertiesStatement.setString(2, key);
          insertPropertiesStatement.setString(3, value);

          if (cnxSupportsBatchUpdates) {
            insertPropertiesStatement.addBatch();
          } else {
            insertPropertiesStatement.execute();
          }
        }

        if (cnxSupportsBatchUpdates) {
          insertPropertiesStatement.executeBatch();
        }

        insertPropertiesStatement.close();
        insertPropertiesStatement = null;
      }

      String[] strRep = event.getThrowableStrRep();

      if (strRep != null) {
        LogLog.debug("Logging an exception");

        PreparedStatement insertExceptionStatement =
            connection.prepareStatement(insertExceptionSQL);

        for (short i = 0; i < strRep.length; i++) {
          insertExceptionStatement.setInt(1, eventId);
          insertExceptionStatement.setShort(2, i);
          insertExceptionStatement.setString(3, strRep[i]);
          if (cnxSupportsBatchUpdates) {
            insertExceptionStatement.addBatch();
          } else {
            insertExceptionStatement.execute();
          }
        }
        if (cnxSupportsBatchUpdates) {
          insertExceptionStatement.executeBatch();
        }
        insertExceptionStatement.close();
        insertExceptionStatement = null;
      }

      connection.commit();
    } catch (Throwable sqle) {
      LogLog.error("problem appending event", sqle);
    } finally {
      DBHelper.closeConnection(connection);
    }
  }