@Test
 public void testAppendNonTriggeringEvent() {
   LoggingEvent event = new LoggingEvent();
   event.setThreadName("thead name");
   event.setLevel(Level.DEBUG);
   appender.subAppend(cb, event);
   assertEquals(1, cb.length());
 }
 private ILoggingEvent createLoggingEvent() {
   LoggingEvent le = new LoggingEvent();
   le.setLevel(Level.DEBUG);
   le.setMessage("test message");
   le.setTimeStamp(System.currentTimeMillis());
   le.setThreadName(Thread.currentThread().getName());
   return le;
 }
Пример #3
0
 long eventLoop(long len) {
   Logger logger = (Logger) LoggerFactory.getLogger(this.getClass());
   LoggingEvent le = null;
   long start = System.nanoTime();
   for (long i = 0; i < len; i++) {
     le = new LoggingEvent("", logger, Level.DEBUG, "asdasdasd", null, null);
   }
   le.getLevel();
   long end = System.nanoTime();
   return end - start;
 }
Пример #4
0
 private void buildLoggingEventAndAppend(
     final String localFQCN,
     final Marker marker,
     final Level level,
     final String msg,
     final Object[] params,
     final Throwable t) {
   LoggingEvent le = new LoggingEvent(localFQCN, this, level, msg, t, params);
   le.setMarker(marker);
   callAppenders(le);
 }
Пример #5
0
  /**
   * Create an {@link IStatus} from the given event
   *
   * @param event the logging event
   * @param multi if a {@link CustomMultiStatus} shall be created
   * @param hasParent if the status has a parent
   * @return the {@link IStatus} or <code>null</code>
   */
  private IStatus createStatus(LoggingEvent event, boolean multi, boolean hasParent) {
    // pluginId
    String pluginId = ALoggerUtil.getBundleName(event.getMarker());
    if (pluginId == null) {
      // default to logger name
      String name = event.getLoggerName();
      if (name != null) {
        pluginId = "[" + name + "]";
      }

      if (pluginId == null) {
        pluginId = "#unknown";
      }
    }

    // throwable
    Throwable throwable;
    if (event.getThrowableProxy() != null && event.getThrowableProxy() instanceof ThrowableProxy) {
      throwable = ((ThrowableProxy) event.getThrowableProxy()).getThrowable();
    } else {
      throwable = null;
    }

    String message = event.getFormattedMessage();
    if (hasParent) {
      // include time in message
      // (as it gets lost in MultiStatus)
      Date date = new Date(event.getTimeStamp());
      message = "[" + TIME_FORMAT.format(date) + "] " + message;
    }

    // create status object
    IStatus status;
    if (multi) {
      status = new CustomMultiStatus(pluginId, IStatus.OK, message, throwable);
    } else {
      // severity
      Level level = event.getLevel();

      if (!level.isGreaterOrEqual(Level.INFO)) {
        return null;
      }

      int severity;
      if (level == Level.INFO) {
        severity = IStatus.INFO;
      } else if (level == Level.WARN) {
        severity = IStatus.WARNING;
      } else {
        // default to error
        severity = IStatus.ERROR;
      }

      status = new Status(severity, pluginId, message, throwable);
    }

    return status;
  }
 protected void preProcess(LoggingEvent event) {
   if (event != null) {
     if (includeCallerData) {
       event.getCallerData();
     }
   }
 }
Пример #7
0
 protected void append(ch.qos.logback.classic.spi.LoggingEvent event) {
   if (event != null && FILE_BUFFER != null) // just to make sure...
   {
     localId++;
     event.getCallerData();
     LoggingEvent lilithEvent = converter.convert(event);
     EventWrapper<LoggingEvent> wrapper =
         new EventWrapper<>(SOURCE_IDENTIFIER, localId, lilithEvent);
     FILE_BUFFER.add(wrapper);
   }
 }
Пример #8
0
 @SuppressWarnings("unchecked")
 private static void writeEvent(LoggingEvent evt, Appender appender) {
   if (null == evt) {
     return;
   }
   if (null != appender) {
     appender.doAppend(evt);
   } else {
     System.out.println(evt.getFormattedMessage());
   }
 }
Пример #9
0
  @SuppressWarnings("unchecked")
  private static LoggingEvent readLoggingEvent(ExcerptTailer ex, LoggerContext ctx) {
    LoggingEventRecord rec = LoggingEventRecord.read(ex);

    Logger logger = ctx.getLogger(rec.getLoggerName());
    LoggingEvent evt =
        new LoggingEvent(
            logger.getClass().getName(),
            logger,
            Level.toLevel(rec.getLevel()),
            rec.getMessage(),
            rec.getCause(),
            rec.getArgs());
    evt.setTimeStamp(rec.getTimestamp());
    evt.setThreadName(rec.getThreadName());
    evt.setMDCPropertyMap(rec.getMdcProps());
    if (null != rec.getCause()) {
      evt.setThrowableProxy(new ThrowableProxy(rec.getCause()));
    }
    evt.setCallerData(rec.getCallerData());

    return evt;
  }
Пример #10
0
    @Override
    public void run() {
      try {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        while (true) {
          final Event event = events.take();
          ILoggingEvent logEvent = event.getEvent();

          String name = logEvent.getLoggerName();
          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 timestamp
          Calendar tstamp = Calendar.getInstance();
          tstamp.setTimeInMillis(logEvent.getTimeStamp());
          amqpProps.setTimestamp(tstamp.getTime());

          // Copy properties in from MDC
          Map<String, String> props = event.getProperties();
          Set<Entry<String, String>> entrySet = props.entrySet();
          for (Entry<String, String> entry : entrySet) {
            amqpProps.setHeader(entry.getKey(), entry.getValue());
          }
          String[] location = locationLayout.doLayout(logEvent).split("\\|");
          if (!"?".equals(location[0])) {
            amqpProps.setHeader(
                "location", String.format("%s.%s()[%s]", location[0], location[1], location[2]));
          }
          String msgBody;
          String routingKey = routingKeyLayout.doLayout(logEvent);
          // Set applicationId, if we're using one
          if (applicationId != null) {
            amqpProps.setAppId(applicationId);
          }

          if (abbreviator != null && logEvent instanceof LoggingEvent) {
            ((LoggingEvent) logEvent).setLoggerName(abbreviator.abbreviate(name));
            msgBody = layout.doLayout(logEvent);
            ((LoggingEvent) logEvent).setLoggerName(name);
          } else {
            msgBody = layout.doLayout(logEvent);
          }

          // Send a message
          try {
            Message message = null;
            if (AmqpAppender.this.charset != null) {
              try {
                message = new Message(msgBody.getBytes(AmqpAppender.this.charset), amqpProps);
              } catch (UnsupportedEncodingException e) {
                message = new Message(msgBody.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 {
              addError(
                  "Could not send log message "
                      + logEvent.getMessage()
                      + " after "
                      + maxSenderRetries
                      + " retries",
                  e);
            }
          }
        }
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
    }
Пример #11
0
 @Test
 public void marker() throws EvaluationException {
   LoggingEvent event = makeEvent("x");
   event.setMarker(markerA);
   doEvaluateAndCheck("e.marker?.name == 'A'", event, true);
 }
Пример #12
0
  @SuppressWarnings("unchecked")
  public static void main(String... args) throws ParseException, JoranException, IOException {
    Parser parser = new BasicParser();
    CommandLine cl = null;
    try {
      cl = parser.parse(OPTS, args);
    } catch (ParseException e) {
      HelpFormatter help = new HelpFormatter();
      help.printHelp("dlog", OPTS, true);
      System.exit(-1);
    }

    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    loggerContext.reset();

    if (cl.hasOption("config")) {
      // Read Logback configuration
      JoranConfigurator configurator = new JoranConfigurator();
      configurator.setContext(loggerContext);

      configurator.doConfigure(cl.getOptionValue("file", "logback.xml"));

      StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext);
    } else {
      BasicConfigurator.configure(loggerContext);
    }

    Appender appender = null;
    if (cl.hasOption("output")) {
      String outputAppender = cl.getOptionValue("output", "console");
      appender = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME).getAppender(outputAppender);
    }

    ChronicleTools.warmup();
    Chronicle chronicle = new IndexedChronicle(cl.getOptionValue("path"), ChronicleConfig.DEFAULT);
    ExcerptTailer ex = chronicle.createTailer();

    Level level = Level.valueOf(cl.getOptionValue("level", "TRACE"));

    if (cl.hasOption("head")) {
      int lines = Integer.parseInt(cl.getOptionValue("head", "10"));
      for (int i = 0; i < lines; i++) {
        LoggingEvent evt = readLoggingEvent(ex, loggerContext);
        if (evt.getLevel().isGreaterOrEqual(level)) {
          writeEvent(evt, appender);
        }
      }
    } else if (cl.hasOption("tail")) {
      int lines = Integer.parseInt(cl.getOptionValue("tail", "10"));
      Queue<LoggingEvent> tail = new LinkedBlockingQueue<LoggingEvent>(lines);
      while (ex.nextIndex()) {
        LoggingEvent evt = readLoggingEvent(ex, loggerContext);
        if (!tail.offer(evt)) {
          tail.poll();
          tail.add(evt);
        }
      }
      LoggingEvent evt;
      while (null != (evt = tail.poll())) {
        if (evt.getLevel().isGreaterOrEqual(level)) {
          writeEvent(evt, appender);
        }
      }
    } else if (cl.hasOption("search")) {
      String regex = cl.getOptionValue("search");
      Pattern regexPatt = Pattern.compile(regex);
      while (ex.nextIndex()) {
        LoggingEvent evt = readLoggingEvent(ex, loggerContext);
        if (null != evt && evt.getLevel().isGreaterOrEqual(level)) {
          if (regexPatt.matcher(evt.getFormattedMessage()).matches()) {
            writeEvent(evt, appender);
          }
        }
      }
    }

    loggerContext.stop();
    chronicle.close();
  }
Пример #13
0
 /** @see GroupAwareLogObserver#acceptRawEvent(ch.qos.logback.classic.spi.LoggingEvent) */
 @Override
 protected boolean acceptRawEvent(LoggingEvent event) {
   Level level = event.getLevel();
   return level == Level.INFO || level == Level.WARN || level == Level.ERROR;
 }