Java Code Examples for org.apache.log4j.spi.LoggingEvent#getMessage()

The following examples show how to use org.apache.log4j.spi.LoggingEvent#getMessage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StaticLog4jFormatter.java    From suro with Apache License 2.0 6 votes vote down vote up
@Override
public String format(LoggingEvent event) {
    StringBuilder sb = new StringBuilder();
    sb.append(fmt.print(new DateTime())).append('\t');
    sb.append(event.getLevel()).append('\t').append(event.getLoggerName());

    Object obj = event.getMessage();

    sb.append('\t').append(obj.toString());

    // Extract exceptions
    String[] s = event.getThrowableStrRep();
    if (s != null && s.length > 0) {
        sb.append('\n').append(s[0]);
        for (int i = 1; i < s.length; i++) {
            sb.append('\n').append(s[i]);
        }
    }

    return sb.toString();
}
 
Example 2
Source File: CamelLanguageServerTest.java    From camel-language-server with Apache License 2.0 6 votes vote down vote up
@Test
void testDONTProvideCompletionWhenNotAfterURIEqualQuote() throws Exception {
	final TestLogAppender appender = new TestLogAppender();
	final Logger logger = Logger.getRootLogger();
	logger.addAppender(appender);
	CamelLanguageServer camelLanguageServer = initializeLanguageServer("<from uri=\"\" xmlns=\"http://camel.apache.org/schema/spring\"></from>\n");
	
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(camelLanguageServer, new Position(0, 6));
	
	assertThat(completions.get().getLeft()).isEmpty();
	assertThat(completions.get().getRight()).isNull();
	for (LoggingEvent loggingEvent : appender.getLog()) {
		if (loggingEvent.getMessage() != null) {
			assertThat((String)loggingEvent.getMessage()).doesNotContain(CamelEndpointCompletionProcessor.ERROR_SEARCHING_FOR_CORRESPONDING_NODE_ELEMENTS);
		}
	}
}
 
Example 3
Source File: Console.java    From olca-app with Mozilla Public License 2.0 6 votes vote down vote up
@Override
protected void append(LoggingEvent evt) {
	if (stream.isClosed())
		return;
	String message;
	if (evt.getLevel().toInt() <= Level.DEBUG_INT) {
		LocationInfo info = evt.getLocationInformation();
		message = "" + evt.getLevel().toString()
				+ " [" + DateFormatUtils.format(evt.timeStamp, "HH:mm:ss.SS") + "]"
				+ " @" + info.getClassName()
				+ ">" + info.getMethodName()
				+ ">" + info.getLineNumber()
				+ " - " + evt.getMessage();
	} else {
		message = "" + evt.getLevel().toString()
				+ " - " + evt.getMessage();
	}
	tryPrintMessage(message, evt.getThrowableInformation());
}
 
Example 4
Source File: JmxAttributeStatisticsAppender.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void append(LoggingEvent event) {
   Object logMessage = event.getMessage();
   if (logMessage instanceof GroupedTimingStatistics && this.mBean != null) {
      this.mBean.updateCurrentTimingStatistics((GroupedTimingStatistics)logMessage);
   }

}
 
Example 5
Source File: JsonLog4jFormatter.java    From suro with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public String format(LoggingEvent event) {
    Object obj = event.getMessage();

    routingKey = null;

    if (obj instanceof Map) {
        Map map = (Map) event.getMessage();
        DateTime now = new DateTime();
        map.put("ts", now.getMillis());
        map.put("datetime", fmt.print(now));
        map.put("logLevel", event.getLevel().toString());
        map.put("class", event.getLoggerName());

        routingKey = (String) map.get(TagKey.ROUTING_KEY);

        // Extract exceptions
        String[] s = event.getThrowableStrRep();
        if (s != null && s.length > 0) {
            map.put("Exception", s);
        }
        try {
            return jsonMapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            jsonParsingError.incrementAndGet();
            return stringFormatter.format(event);
        }
    } else {
        jsonParsingError.incrementAndGet();
        return stringFormatter.format(event);
    }
}
 
Example 6
Source File: LCSLog4jAppender.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
protected void append(LoggingEvent loggingEvent) {
  Message message;
  if (loggingEvent.getMessage() instanceof Message) {
    message = (Message) loggingEvent.getMessage();
  } else {
    String value = layout.format(loggingEvent);
    if (layout.ignoresThrowable()) {
      String[] lineList = loggingEvent.getThrowableStrRep();
      if (lineList != null) {
        for (String line : lineList) {
          value += line + Layout.LINE_SEP;
        }
      }
    }

    message = new Message();
    message.setCreateTimestamp(System.currentTimeMillis());
    message.setMessageType(MessageType.BINARY);
    try {
      message.setMessage(value.getBytes(encoding));
    } catch (Exception e) {
      logger.error("appendMessage failed", e);
      return;
    }
  }
  lcsAppender.addMessage(message);
}
 
Example 7
Source File: QueuePurgeTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void testPurgeLargeQueue() throws Exception {
   applyBrokerSpoolingPolicy();
   createProducerAndSendMessages(NUM_TO_SEND);
   QueueViewMBean proxy = getProxyToQueueViewMBean();
   LOG.info("purging..");

   org.apache.log4j.Logger log4jLogger = org.apache.log4j.Logger.getLogger(org.apache.activemq.broker.region.Queue.class);
   final AtomicBoolean gotPurgeLogMessage = new AtomicBoolean(false);

   Appender appender = new DefaultTestAppender() {
      @Override
      public void doAppend(LoggingEvent event) {
         if (event.getMessage() instanceof String) {
            String message = (String) event.getMessage();
            if (message.contains("purged of " + NUM_TO_SEND + " messages")) {
               LOG.info("Received a log message: {} ", event.getMessage());
               gotPurgeLogMessage.set(true);
            }
         }
      }
   };

   Level level = log4jLogger.getLevel();
   log4jLogger.setLevel(Level.INFO);
   log4jLogger.addAppender(appender);
   try {

      proxy.purge();

   } finally {
      log4jLogger.setLevel(level);
      log4jLogger.removeAppender(appender);
   }

   assertEquals("Queue size is not zero, it's " + proxy.getQueueSize(), 0, proxy.getQueueSize());
   assertTrue("cache is disabled, temp store being used", !proxy.isCacheEnabled());
   assertTrue("got expected info purge log message", gotPurgeLogMessage.get());
}
 
Example 8
Source File: Log4JTaskLogs.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private void appendEventToLogs(LoggingEvent logEvent, StringBuffer logs, Layout logFormat, boolean timeStamp) {
    if (timeStamp) {
        logs.append(StringUtils.stripEnd(logFormat.format(logEvent), null) + nl);
    } else {
        Object message = logEvent.getMessage();
        logs.append(StringUtils.stripEnd(message.toString(), null) + nl);
    }
}
 
Example 9
Source File: UnifiedSystemLogAppender.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void append(final LoggingEvent event) {
    if(null == event.getMessage()) {
        return;
    }
    // Category name
    final String logger = String.format("%s %s", event.getThreadName(), event.getLogger().getName());
    switch(event.getLevel().toInt()) {
        case Level.FATAL_INT:
        case Level.ERROR_INT:
            this.log(OS_LOG_TYPE_ERROR, logger, event.getMessage().toString());
            break;
        case Level.TRACE_INT:
        case Level.DEBUG_INT:
            this.log(OS_LOG_TYPE_DEBUG, logger, event.getMessage().toString());
            break;
        case Level.INFO_INT:
            this.log(OS_LOG_TYPE_INFO, logger, event.getMessage().toString());
            break;
        case Level.WARN_INT:
        default:
            this.log(OS_LOG_TYPE_DEFAULT, logger, event.getMessage().toString());
            break;
    }
    if(layout.ignoresThrowable()) {
        // Appender responsible for rendering
        final String[] trace = event.getThrowableStrRep();
        if(trace != null) {
            for(final String t : trace) {
                this.log(OS_LOG_TYPE_DEFAULT, logger, t);
            }
        }
    }
}
 
Example 10
Source File: TerminalAppender.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void append(final LoggingEvent event) {
    if(null == event.getMessage()) {
        return;
    }
    final StringBuilder buffer = new StringBuilder();
    buffer.append(layout.format(event));
    console.printf("\r%s%s%s", Ansi.ansi()
            .fg(Ansi.Color.YELLOW)
            .saveCursorPosition()
            .eraseLine(Ansi.Erase.ALL)
            .restoreCursorPosition(), buffer.toString(),
        Ansi.ansi().reset());
}
 
Example 11
Source File: JSONLayout.java    From multi-model-server with Apache License 2.0 5 votes vote down vote up
@Override
public String format(LoggingEvent event) {
    Object eventMessage = event.getMessage();
    if (eventMessage == null) {
        return null;
    }
    if (eventMessage instanceof Metric) {
        Metric metric = (Metric) event.getMessage();
        return JsonUtils.GSON_PRETTY.toJson(metric) + '\n';
    }
    return eventMessage.toString() + '\n';
}
 
Example 12
Source File: PopupAppender.java    From olca-app with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected void append(LoggingEvent event) {
	if (event == null || !event.getLevel().isGreaterOrEqual(Level.ERROR))
		return;
	if (!PlatformUI.isWorkbenchRunning()
			|| openPopupCount.get() >= MAX_POPUPS) {
		return;
	}

	try {
		openPopupCount.incrementAndGet();
		new PopupTokenWatch().start();
		String message = event.getMessage() != null
				? event.getMessage().toString() + "<br/>"
				: "";
		message += "<b>See the log file (under Help)"
				+ " for further information.</b>";

		Popup.error("An internal error occurred", message);
	} catch (Exception e) {
		// If the creation of the popup creates an error itself
		// handle it here.
		if (failureCounter.incrementAndGet() > 3) {
			log.warn("Showing of failed error popups "
					+ "stopped because of repetetive failures");
		} else {
			log.error("Show message failed", e);
		}
	}
}
 
Example 13
Source File: StringLog4jFormatter.java    From suro with Apache License 2.0 5 votes vote down vote up
@Override
public String format(LoggingEvent event) {
    StringBuilder sb = new StringBuilder();
    sb.append(fmt.print(new DateTime())).append(fieldDelim);
    sb.append(event.getLevel()).append(fieldDelim).append(event.getLoggerName());

    Object obj = event.getMessage();

    routingKey = null;

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

    // Extract exceptions
    String[] s = event.getThrowableStrRep();
    if (s != null && s.length > 0) {
        sb.append(fieldDelim).append("Exception").append(fieldEqual).append(s[0]);
        for (int i = 1; i < s.length; i++) {
            sb.append('\n').append(s[i]);
        }
    }

    return sb.toString();
}
 
Example 14
Source File: LogsearchConversion.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
public String getLogMessage(LoggingEvent event) {
  String logMessage = event.getMessage() != null ? event.getMessage().toString() : "";

  if (event.getThrowableInformation() != null && event.getThrowableInformation().getThrowable() != null) {
    logMessage += NEW_LINE;
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    event.getThrowableInformation().getThrowable().printStackTrace(pw);
    logMessage += sw.toString();
  }

  return logMessage;
}
 
Example 15
Source File: GelfJsonAppender.java    From xian with Apache License 2.0 5 votes vote down vote up
@Override
protected void append(final LoggingEvent event) {
    GelfMessage gelfMessage = GelfMessageFactory.makeMessage(layout, event, this);
    String originalMessage;
    if (event != null && event.getMessage() != null) {
        originalMessage = event.getMessage().toString().trim();
        if (originalMessage.startsWith("{")/* && originalMessage.endsWith("}")*/) {
            try {
                JSONObject fields = (JSONObject) JSON.parse(originalMessage);
                for (String key : fields.keySet()) {
                    gelfMessage.getAdditonalFields().put(key, fields.get(key));
                }
            } catch (JSONException ignored) {
                //ignored because the log content is not a json string.
            }
        }
    }
    if (getGelfSender() == null) {
        errorHandler.error("Could not send GELF message. Gelf Sender is not initialised and equals null");
    } else {
        GelfSenderResult gelfSenderResult = getGelfSender().sendMessage(gelfMessage);
        if (!GelfSenderResult.OK.equals(gelfSenderResult)) {
            errorHandler.error("Error during sending GELF message. Error code: " + gelfSenderResult.getCode() + ".",
                    gelfSenderResult.getException(), ErrorCode.WRITE_FAILURE);
        }
    }
}
 
Example 16
Source File: GraphingStatisticsAppender.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void append(LoggingEvent event) {
   Object logMessage = event.getMessage();
   if (logMessage instanceof GroupedTimingStatistics && this.chartGenerator != null) {
      this.chartGenerator.appendData((GroupedTimingStatistics)logMessage);
      this.hasUnflushedData = true;
      this.lastAppendedEventLevel = event.getLevel();
      if (this.numLoggedStatistics.incrementAndGet() % (long)this.getDataPointsPerGraph() == 0L) {
         this.flush();
      }
   }

}
 
Example 17
Source File: JSONLayout.java    From serve with Apache License 2.0 5 votes vote down vote up
@Override
public String format(LoggingEvent event) {
    Object eventMessage = event.getMessage();
    if (eventMessage == null) {
        return null;
    }
    if (eventMessage instanceof Metric) {
        Metric metric = (Metric) event.getMessage();
        return JsonUtils.GSON_PRETTY.toJson(metric) + '\n';
    }
    return eventMessage.toString() + '\n';
}
 
Example 18
Source File: Log4jKettleLayout.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public String format( LoggingEvent event ) {
  // OK, perhaps the logging information has multiple lines of data.
  // We need to split this up into different lines and all format these
  // lines...
  //
  StringBuffer line = new StringBuffer();

  String dateTimeString = "";
  if ( timeAdded ) {
    dateTimeString = LOCAL_SIMPLE_DATE_PARSER.get().format( new Date( event.timeStamp ) ) + " - ";
  }

  Object object = event.getMessage();
  if ( object instanceof LogMessage ) {
    LogMessage message = (LogMessage) object;

    String[] parts = message.getMessage().split( Const.CR );
    for ( int i = 0; i < parts.length; i++ ) {
      // Start every line of the output with a dateTimeString
      line.append( dateTimeString );

      // Include the subject too on every line...
      if ( message.getSubject() != null ) {
        line.append( message.getSubject() );
        if ( message.getCopy() != null ) {
          line.append( "." ).append( message.getCopy() );
        }
        line.append( " - " );
      }

      if ( message.isError() ) {
        BuildVersion buildVersion = BuildVersion.getInstance();
        line.append( ERROR_STRING );
        line.append( " (version " );
        line.append( buildVersion.getVersion() );
        if ( !Utils.isEmpty( buildVersion.getRevision() ) ) {
          line.append( ", build " );
          line.append( buildVersion.getRevision() );
        }
        if ( !Utils.isEmpty( buildVersion.getBuildDate() ) ) {
          line.append( " from " );
          line.append( buildVersion.getBuildDate() );
        }
        if ( !Utils.isEmpty( buildVersion.getBuildUser() ) ) {
          line.append( " by " );
          line.append( buildVersion.getBuildUser() );
        }
        line.append( ") : " );
      }

      line.append( parts[i] );
      if ( i < parts.length - 1 ) {
        line.append( Const.CR ); // put the CR's back in there!
      }
    }
  } else {
    line.append( dateTimeString );
    line.append( ( object != null ? object.toString() : "<null>" ) );
  }

  return line.toString();
}
 
Example 19
Source File: LoghubAppender.java    From aliyun-log-log4j-appender with Apache License 2.0 4 votes vote down vote up
@Override
protected void append(LoggingEvent event) {
  LogItem logItem = new LogItem();
  logItem.SetTime((int) (event.getTimeStamp() / 1000));
  DateTime dateTime = new DateTime(event.getTimeStamp());
  logItem.PushBack("time", dateTime.toString(formatter));
  logItem.PushBack("level", event.getLevel().toString());
  logItem.PushBack("thread", event.getThreadName());
  logItem.PushBack("location", event.getLocationInformation().fullInfo);
  Object message = event.getMessage();
  if(message==null){
    logItem.PushBack("message", "");
  }else{
    logItem.PushBack("message", event.getMessage().toString());
  }

  String throwable = getThrowableStr(event);
  if (throwable != null) {
    logItem.PushBack("throwable", throwable);
  }

  if (getLayout() != null) {
    logItem.PushBack("log", getLayout().format(event));
  }

  Map properties = event.getProperties();
  if (properties.size() > 0) {
    Object[] keys = properties.keySet().toArray();
    Arrays.sort(keys);
    for (int i = 0; i < keys.length; i++) {
      logItem.PushBack(keys[i].toString(), properties.get(keys[i])
          .toString());
    }
  }
  try {
    producer.send(projectConfig.getProject(), logStore, topic, source, logItem,
        new LoghubAppenderCallback(projectConfig.getProject(), logStore, topic, source, logItem));
  } catch (Exception e) {
    LogLog.error(
        "Failed to send log, project=" + project
            + ", logStore=" + logStore
            + ", topic=" + topic
            + ", source=" + source
            + ", logItem=" + logItem, e);
  }
}
 
Example 20
Source File: TestLogAppender.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Override
protected void append(LoggingEvent event) {
    if (event.getMessage() != null) {
        messages.add(event.getMessage().toString());
    }
}