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

The following examples show how to use org.apache.log4j.spi.LoggingEvent#getRenderedMessage() . 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: ZPublisher4J.java    From bidder with Apache License 2.0 6 votes vote down vote up
/**
 * Append the log to ZPublisher
 * @param event LoggingEvent. The log event to format and send to the log receiver.
 */
protected void append(LoggingEvent event) {
	if (publisher == null)
		return;
	String name = event.getLocationInformation().getClassName();
	name = name.substring(name.lastIndexOf(".")+1);
	String level = event.getLevel().toString();
	String message = event.getRenderedMessage();
	String line = event.getLocationInformation().getLineNumber();
	Map s = new HashMap();
	s.put("instance",Configuration.instanceName);
	s.put("sev", level);
	s.put("source", name);
	s.put("field", line);
	s.put("message", message);

	publisher.add(s);
}
 
Example 2
Source File: AlertsSyslogAppender.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Override
protected void append(LoggingEvent event) {
    if (!isAsSevereAsThreshold(event.getLevel())) {
        return;
    }

    if (_syslogAppenders != null && !_syslogAppenders.isEmpty()) {
        try {
            String logMessage = event.getRenderedMessage();
            if (logMessage.contains("alertType") && logMessage.contains("message")) {
                parseMessage(logMessage);
                String syslogMessage = createSyslogMessage();

                LoggingEvent syslogEvent = new LoggingEvent(event.getFQNOfLoggerClass(), event.getLogger(), event.getLevel(), syslogMessage, null);

                for (SyslogAppender syslogAppender : _syslogAppenders) {
                    syslogAppender.append(syslogEvent);
                }
            }
        } catch (Exception e) {
            errorHandler.error(e.getMessage());
        }
    }
}
 
Example 3
Source File: ZPublisher4J.java    From XRTB with Apache License 2.0 6 votes vote down vote up
/**
 * Append the log to ZPublisher
 * @param event LoggingEvent. The log event to format and send to the log receiver.
 */
protected void append(LoggingEvent event) {
	if (publisher == null)
		return;
	String name = event.getLocationInformation().getClassName();
	name = name.substring(name.lastIndexOf(".")+1);
	String level = event.getLevel().toString();
	String message = event.getRenderedMessage();
	String line = event.getLocationInformation().getLineNumber();
	Map s = new HashMap();
	s.put("sev", level);
	s.put("source", name);
	s.put("field", line);
	s.put("message", message);
	publisher.add(s);
}
 
Example 4
Source File: Log4jConfigurationManager.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
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 5
Source File: StringMatchFilter.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
    Returns {@link Filter#NEUTRAL} is there is no string match.
  */
 public
 int decide(LoggingEvent event) {
   String msg = event.getRenderedMessage();

   if(msg == null ||  stringToMatch == null)
     return Filter.NEUTRAL;
   

   if( msg.indexOf(stringToMatch) == -1 ) {
     return Filter.NEUTRAL;
   } else { // we've got a match
     if(acceptOnMatch) {
return Filter.ACCEPT;
     } else {
return Filter.DENY;
     }
   }
 }
 
Example 6
Source File: AuditLayout.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public String format( LoggingEvent event ) {
  sb.setLength( 0 );
  dateFormat( sb, event );
  CorrelationContext cc = (CorrelationContext)event.getMDC( Log4jCorrelationService.MDC_CORRELATION_CONTEXT_KEY );
  AuditContext ac = (AuditContext)event.getMDC( Log4jAuditService.MDC_AUDIT_CONTEXT_KEY );
  appendParameter( cc == null ? null : cc.getRootRequestId() );
  appendParameter( cc == null ? null : cc.getParentRequestId() );
  appendParameter( cc == null ? null : cc.getRequestId() );
  appendParameter( event.getLoggerName() );
  appendParameter( ac == null ? null : ac.getRemoteIp() );
  appendParameter( ac == null ? null : ac.getTargetServiceName() );
  appendParameter( ac == null ? null : ac.getUsername() );
  appendParameter( ac == null ? null : ac.getProxyUsername() );
  appendParameter( ac == null ? null : ac.getSystemUsername() );
  appendParameter( (String)event.getMDC( AuditConstants.MDC_ACTION_KEY ) );
  appendParameter( (String)event.getMDC( AuditConstants.MDC_RESOURCE_TYPE_KEY ) );
  appendParameter( (String)event.getMDC( AuditConstants.MDC_RESOURCE_NAME_KEY ) );
  appendParameter( (String)event.getMDC( AuditConstants.MDC_OUTCOME_KEY ) );
  String message = event.getRenderedMessage();
  sb.append( message == null ? "" : message ).append( LINE_SEP );
  return sb.toString();
}
 
Example 7
Source File: LoggingTester.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void append(final LoggingEvent event) {
  String _renderedMessage = event.getRenderedMessage();
  String _loggerName = event.getLoggerName();
  long _timeStamp = event.getTimeStamp();
  Level _level = event.getLevel();
  final LoggingTester.LogEntry entry = new LoggingTester.LogEntry(_renderedMessage, _loggerName, _timeStamp, _level);
  this.events.add(entry);
}
 
Example 8
Source File: JDBCLog.java    From MultimediaDesktop with Apache License 2.0 5 votes vote down vote up
public void append(LoggingEvent event) {
	event.getNDC();
	event.getThreadName();
	// Get a copy of this thread's MDC.
	event.getMDCCopy();
	if (locationInfo) {
		event.getLocationInformation();
	}
	event.getRenderedMessage();
	event.getThrowableStrRep();
	buffer.add(event);

	if (buffer.size() >= bufferSize)
		flushBuffer();
}
 
Example 9
Source File: OutputCaptor.java    From validatar with Apache License 2.0 5 votes vote down vote up
protected boolean isStringInLog(String message, boolean isCaseSensitive) {
    ArgumentCaptor<LoggingEvent> arguments = ArgumentCaptor.forClass(LoggingEvent.class);
    verify(mockedAppender, atLeastOnce()).doAppend(arguments.capture());
    List<LoggingEvent> events = arguments.getAllValues();
    for (LoggingEvent event : events) {
        String log = event.getRenderedMessage();
        if (contains(log, message, isCaseSensitive)) {
            return true;
        }
    }
    return false;
}
 
Example 10
Source File: LoggingTester.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void append(final LoggingEvent event) {
  String _renderedMessage = event.getRenderedMessage();
  String _loggerName = event.getLoggerName();
  long _timeStamp = event.getTimeStamp();
  Level _level = event.getLevel();
  final LoggingTester.LogEntry entry = new LoggingTester.LogEntry(_renderedMessage, _loggerName, _timeStamp, _level);
  this.events.add(entry);
}
 
Example 11
Source File: LogVerificationAppender.java    From big-c with Apache License 2.0 5 votes vote down vote up
public int countLinesWithMessage(final String text) {
  int count = 0;
  for (LoggingEvent e: getLog()) {
    String msg = e.getRenderedMessage();
    if (msg != null && msg.contains(text)) {
      count++;
    }
  }
  return count;
}
 
Example 12
Source File: MaskPatternLayout.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String format(LoggingEvent event) {
    if (maskPattern == null || !(event.getMessage() instanceof String)) {
        return super.format(event);
    }

    String message = event.getRenderedMessage();
    String maskedMessage = maskMessage(message, maskPattern, maskString);
    Throwable throwable = event.getThrowableInformation() != null ?
            event.getThrowableInformation().getThrowable() : null;
    LoggingEvent maskedEvent = new LoggingEvent(event.fqnOfCategoryClass,
                Logger.getLogger(event.getLoggerName()), event.timeStamp,
                event.getLevel(), maskedMessage, throwable);
    return super.format(maskedEvent);
}
 
Example 13
Source File: KafkaAppender.java    From SkyEye with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 获得message
 * @param event
 * @return
 */
private String getMessage(LoggingEvent event) {
    if (this.layout == null) {
        return event.getRenderedMessage();
    } else {
        // 获取host和app
        String msg = System.nanoTime() + Constants.SEMICOLON + this.layout.format(event);
        return msg.replaceFirst(Constants.APP_NAME, this.app).replaceFirst(Constants.HOSTNAME, this.host);
    }
}
 
Example 14
Source File: LogVerificationAppender.java    From hadoop with Apache License 2.0 5 votes vote down vote up
public int countLinesWithMessage(final String text) {
  int count = 0;
  for (LoggingEvent e: getLog()) {
    String msg = e.getRenderedMessage();
    if (msg != null && msg.contains(text)) {
      count++;
    }
  }
  return count;
}
 
Example 15
Source File: DatabaseTest.java    From database with Apache License 2.0 4 votes vote down vote up
/**
 * Check for a log entry with a particular log level and message.
 *
 * <p>The message pattern is a literal, exactly matching string,
 * but it may contain a few special tokens that will match varying
 * input in the messages:</p>
 *
 * <ul>
 *   <li>${timing} - this will match a typical section of metrics</li>
 *   <li>${sep} - this will match the boundary between the raw SQL and
 *                the debug sql that logs the parameters as well</li>
 * </ul>
 *
 * @param level the specific level we are looking for
 * @param messagePattern a search pattern (see notes above)
 */
public synchronized void assertMessage(Level level, String messagePattern) {
  boolean found = false;
  for (LoggingEvent event : events) {
    if (!event.getLevel().equals(level)) {
      continue;
    }

    String message = event.getRenderedMessage();
    int messagePos = 0;
    int patternPos = 0;
    while (messagePos < message.length() && patternPos < messagePattern.length()) {
      // Advance until we find a character that doesn't match
      if (message.charAt(messagePos) == messagePattern.charAt(patternPos)) {
        messagePos++;
        patternPos++;
        continue;
      }

      // If message has literal '$' terminate because the pattern doesn't have a special matcher
      if (message.charAt(messagePos) == '$') {
        break;
      }

      // Special matchers: expressions for things that vary with each run
      if (messagePattern.startsWith("${timing}", patternPos) && message.indexOf(')', messagePos) != -1) {
        messagePos = message.indexOf(')', messagePos) + 1;
        patternPos += "${timing}".length();
        continue;
      }
      if (messagePattern.startsWith("${sep}", patternPos)
          && message.startsWith(DebugSql.PARAM_SQL_SEPARATOR, messagePos)) {
        messagePos += DebugSql.PARAM_SQL_SEPARATOR.length();
        patternPos += "${sep}".length();
        continue;
      }

      // Couldn't match
      break;
    }

    if (messagePos >= message.length() && patternPos >= messagePattern.length()) {
      found = true;
      break;
    }
  }
  assertTrue("Log message not found (" + level + " " + messagePattern + ") in log:\n" + toString(), found);
}
 
Example 16
Source File: LF5Appender.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Appends a <code>LoggingEvent</code> record to the
 * <code>LF5Appender</code>.
 * @param event The <code>LoggingEvent</code>
 * to be appended.
 */
public void append(LoggingEvent event) {
  // Retrieve the information from the log4j LoggingEvent.
  String category = event.getLoggerName();
  String logMessage = event.getRenderedMessage();
  String nestedDiagnosticContext = event.getNDC();
  String threadDescription = event.getThreadName();
  String level = event.getLevel().toString();
  long time = event.timeStamp;
  LocationInfo locationInfo = event.getLocationInformation();

  // Add the logging event information to a LogRecord
  Log4JLogRecord record = new Log4JLogRecord();

  record.setCategory(category);
  record.setMessage(logMessage);
  record.setLocation(locationInfo.fullInfo);
  record.setMillis(time);
  record.setThreadDescription(threadDescription);

  if (nestedDiagnosticContext != null) {
    record.setNDC(nestedDiagnosticContext);
  } else {
    record.setNDC("");
  }

  if (event.getThrowableInformation() != null) {
    record.setThrownStackTrace(event.getThrowableInformation());
  }

  try {
    record.setLevel(LogLevel.valueOf(level));
  } catch (LogLevelFormatException e) {
    // If the priority level doesn't match one of the predefined
    // log levels, then set the level to warning.
    record.setLevel(LogLevel.WARN);
  }

  if (_logMonitor != null) {
    _logMonitor.addMessage(record);
  }
}
 
Example 17
Source File: UnitTestAppender.java    From siddhi-map-json with Apache License 2.0 4 votes vote down vote up
@Override
protected void append(LoggingEvent loggingEvent) {
    messages = loggingEvent.getRenderedMessage();
}
 
Example 18
Source File: HTMLLayout.java    From document-management-software with GNU Lesser General Public License v3.0 4 votes vote down vote up
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>");
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		sbuf.append(df.format(new Date()));
		sbuf.append("</td>" + Layout.LINE_SEP);

		/*
		 * String escapedThread = Transform.escapeTags(event.getThreadName());
		 * sbuf.append("<td title=\"" + escapedThread + " thread\">");
		 * sbuf.append(escapedThread); sbuf.append("</td>" + 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);

		String escapedLogger = Transform.escapeTags(event.getLoggerName());
		sbuf.append("<td title=\"" + escapedLogger + " category\">");
		sbuf.append(escapedLogger);
		sbuf.append("</td>" + Layout.LINE_SEP);

		if (locationInfo) {
			LocationInfo locInfo = event.getLocationInformation();
			sbuf.append("<td>");
			sbuf.append(Transform.escapeTags(locInfo.getFileName()));
			sbuf.append(':');
			sbuf.append(locInfo.getLineNumber());
			sbuf.append("</td>" + Layout.LINE_SEP);
		}

		sbuf.append("<td title=\"Message\">");

		if (event != null && event.getRenderedMessage() != null)
			sbuf.append(Transform.escapeTags(event.getRenderedMessage()).replace("\n", "<br/>"));
		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\">"
			 * );
			 */
			sbuf.append("<tr><td bgcolor=\"#993300\" style=\"color:White; font-size : xx-small;\" colspan=\"5\">");
			appendThrowableAsHTML(s, sbuf);
			sbuf.append("</td></tr>" + Layout.LINE_SEP);
		}

		return sbuf.toString();
	}
 
Example 19
Source File: GlogLayout.java    From xio with Apache License 2.0 4 votes vote down vote up
@Override
public String getMessage(LoggingEvent record) {
  return record.getRenderedMessage();
}
 
Example 20
Source File: FailingAppender.java    From elk-reasoner with Apache License 2.0 4 votes vote down vote up
@Override
protected void append(LoggingEvent event) {
	throw new LoggingException(event.getRenderedMessage());
}