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

The following examples show how to use org.apache.log4j.spi.LoggingEvent#getLocationInformation() . 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: EcsLayout.java    From ecs-logging-java with Apache License 2.0 6 votes vote down vote up
@Override
public String format(LoggingEvent event) {
    StringBuilder builder = new StringBuilder();
    EcsJsonSerializer.serializeObjectStart(builder, event.getTimeStamp());
    EcsJsonSerializer.serializeLogLevel(builder, event.getLevel().toString());
    EcsJsonSerializer.serializeFormattedMessage(builder, event.getRenderedMessage());
    EcsJsonSerializer.serializeServiceName(builder, serviceName);
    EcsJsonSerializer.serializeEventDataset(builder, eventDataset);
    EcsJsonSerializer.serializeThreadName(builder, event.getThreadName());
    EcsJsonSerializer.serializeLoggerName(builder, event.getLoggerName());
    EcsJsonSerializer.serializeMDC(builder, event.getProperties());
    EcsJsonSerializer.serializeTag(builder, event.getNDC());
    if (includeOrigin) {
        LocationInfo locationInformation = event.getLocationInformation();
        if (locationInformation != null) {
            EcsJsonSerializer.serializeOrigin(builder, locationInformation.getFileName(), locationInformation.getMethodName(), getLineNumber(locationInformation));
        }
    }
    ThrowableInformation throwableInformation = event.getThrowableInformation();
    if (throwableInformation != null) {
        EcsJsonSerializer.serializeException(builder, throwableInformation.getThrowable(), stackTraceAsArray);
    }
    EcsJsonSerializer.serializeObjectEnd(builder);
    return builder.toString();
}
 
Example 2
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 3
Source File: SMTPAppender.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
   Perform SMTPAppender specific appending actions, mainly adding
   the event to a cyclic buffer and checking if the event triggers
   an e-mail to be sent. */
public
void append(LoggingEvent event) {

  if(!checkEntryConditions()) {
    return;
  }

  event.getThreadName();
  event.getNDC();
  event.getMDCCopy();
  if(locationInfo) {
    event.getLocationInformation();
  }
  cb.add(event);
  if(evaluator.isTriggeringEvent(event)) {
    sendBuffer();
  }
}
 
Example 4
Source File: JMSAppender.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
    This method called by {@link AppenderSkeleton#doAppend} method to
    do most of the real appending work.  */
 public void append(LoggingEvent event) {
   if(!checkEntryConditions()) {
     return;
   }

   try {
     ObjectMessage msg = topicSession.createObjectMessage();
     if(locationInfo) {
event.getLocationInformation();
     }
     msg.setObject(event);
     topicPublisher.publish(msg);
   } catch(Exception e) {
     errorHandler.error("Could not publish message in JMSAppender ["+name+"].", e,
		 ErrorCode.GENERIC_FAILURE);
   }
 }
 
Example 5
Source File: JulAppender.java    From presto with Apache License 2.0 6 votes vote down vote up
/**
 * Append a log event at the appropriate JUL level, depending on the log4j level.
 */
@Override
protected void append(LoggingEvent loggingEvent)
{
    java.util.logging.Logger logger = java.util.logging.Logger.getLogger(loggingEvent.getLoggerName());
    if (logger == null) {
        LogLog.warn(format("Cannot obtain JUL %s. Verify that this appender is used while an appropriate LogManager is active.", loggingEvent.getLoggerName()));
        return;
    }

    Level level = loggingEvent.getLevel();
    java.util.logging.Level julLevel = convertLog4jLevel(level);

    LogRecord record = new LogRecord(julLevel, loggingEvent.getRenderedMessage());
    record.setMillis(loggingEvent.getTimeStamp());
    LocationInfo location = loggingEvent.getLocationInformation();
    if (location != null) {
        record.setSourceClassName(location.getClassName());
        record.setSourceMethodName(location.getMethodName());
    }

    logger.log(record);
}
 
Example 6
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 7
Source File: PatternParser.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public
   String convert(LoggingEvent event) {
     LocationInfo locationInfo = event.getLocationInformation();
     switch(type) {
     case FULL_LOCATION_CONVERTER:
return locationInfo.fullInfo;
     case METHOD_LOCATION_CONVERTER:
return locationInfo.getMethodName();
     case LINE_LOCATION_CONVERTER:
return locationInfo.getLineNumber();
     case FILE_LOCATION_CONVERTER:
return locationInfo.getFileName();
     default: return null;
     }
   }
 
Example 8
Source File: CassandraAppender.java    From cassandra-log4j-appender with Apache License 2.0 5 votes vote down vote up
/**
   * Send one logging event to Cassandra.  We just bind the new values into the preprocessed query
   * built by setupStatement
   */
  private void createAndExecuteQuery(LoggingEvent event)
  {
BoundStatement bound = new BoundStatement(statement);

      // A primary key combination of timestamp/hostname/threadname should be unique as long as the thread names
      // are set, but would not be backwards compatible.  Do we care?
      bound.setUUID(0, UUID.randomUUID());

      bound.setString(1, appName);
      bound.setString(2, ip);
      bound.setString(3, hostname);
      bound.setString(4, event.getLoggerName());
      bound.setString(5, event.getLevel().toString());

      LocationInfo locInfo = event.getLocationInformation();
      if (locInfo != null) {
          bound.setString(6, locInfo.getClassName());
          bound.setString(7, locInfo.getFileName());
          bound.setString(8, locInfo.getLineNumber());
          bound.setString(9, locInfo.getMethodName());
      }

      bound.setString(10, event.getRenderedMessage());
      bound.setString(11, event.getNDC());
      bound.setLong(12, new Long(LoggingEvent.getStartTime()));
      bound.setString(13, event.getThreadName());

      String[] throwableStrs = event.getThrowableStrRep();
      bound.setString(14, throwableStrs == null ? null : Joiner.on(", ").join(throwableStrs));

      bound.setLong(15, new Long(event.getTimeStamp()));
      session.execute(bound);
  }
 
Example 9
Source File: BenderLayout.java    From bender with Apache License 2.0 5 votes vote down vote up
@Override
public String format(LoggingEvent event) {
  BenderLogEntry entry = new BenderLogEntry();
  entry.threadName = event.getThreadName();
  entry.posixTimestamp = event.getTimeStamp();
  entry.timestamp = FORMATTER.print(entry.posixTimestamp);
  entry.message = event.getRenderedMessage();
  entry.level = event.getLevel().toString();
  entry.logger = event.getLogger().getName();
  entry.alias = ALIAS;
  entry.version = VERSION;

  if (event.getThrowableInformation() != null) {
    final ThrowableInformation throwableInfo = event.getThrowableInformation();
    ExceptionLog ex = new ExceptionLog();

    if (throwableInfo.getThrowable().getClass().getCanonicalName() != null) {
      ex.clazz = throwableInfo.getThrowable().getClass().getCanonicalName();
    }
    if (throwableInfo.getThrowable().getMessage() != null) {
      ex.message = throwableInfo.getThrowable().getMessage();
    }
    if (throwableInfo.getThrowableStrRep() != null) {
      Arrays.asList(throwableInfo.getThrowableStrRep()).forEach(m -> {
        ex.stacktrace.add(m.replaceAll("\\t", "   "));
      });
    }
    entry.exception = ex;
  }

  LocationInfo locinfo = event.getLocationInformation();
  entry.file = locinfo.getFileName();
  entry.lineNumber = Integer.parseInt(locinfo.getLineNumber());
  entry.method = locinfo.getMethodName();
  entry.clazz = locinfo.getClassName();

  return GSON.toJson(entry) + "\n";
}
 
Example 10
Source File: EventDetails.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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);
}
 
Example 11
Source File: JdbmStoreAndForwardAppender.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
protected void append( LoggingEvent event ) {
  try {
    if( fetchLocationInfo ) {
      event.getLocationInformation();
    }
    queue.enqueue( event );
  } catch ( IOException e ) {
    throw new RuntimeException( e );
  }
}
 
Example 12
Source File: SpectatorAppender.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Override protected void append(LoggingEvent event) {
  final LevelTag level = LevelTag.get(event.getLevel());
  registry.counter(numMessages[level.ordinal()]).increment();

  ThrowableInformation info = event.getThrowableInformation();
  if (info != null) {
    LocationInfo loc = event.getLocationInformation();
    final String file = (loc == null) ? "unknown" : loc.getFileName();
    Id stackTraceId = numStackTraces[level.ordinal()]
        .withTag("exception", info.getThrowable().getClass().getSimpleName())
        .withTag("file", file);
    registry.counter(stackTraceId).increment();
  }
}
 
Example 13
Source File: Log4JAppenderWrapper.java    From mrgeo with Apache License 2.0 5 votes vote down vote up
@Override
public void doAppend(LoggingEvent event)
{
  assert (wrappedAppender != null);


  String msg = event.getMessage().toString();

  Matcher m = crlf.matcher(msg);
  if (m.find())
  {
    String lines[] = msg.split("\r\n|\n|\r"); //msg.split("\\r?\\n");

    for (String line : lines)
    {
      String clean = "(Encoded) " + line;

      LoggingEvent encoded = new LoggingEvent(event.getFQNOfLoggerClass(),
          event.getLogger(), event.getTimeStamp(), event.getLevel(), clean,
          event.getThreadName(), event.getThrowableInformation(), event.getNDC(),
          event.getLocationInformation(), event.getProperties());

      wrappedAppender.doAppend(encoded);
    }
  }
  else
  {
    wrappedAppender.doAppend(event);
  }

}
 
Example 14
Source File: AsyncAppender.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void append(final LoggingEvent event) {
  //
  //   if dispatcher thread has died then
  //      append subsequent events synchronously
  //   See bug 23021
  if ((dispatcher == null) || !dispatcher.isAlive() || (bufferSize <= 0)) {
    synchronized (appenders) {
      appenders.appendLoopOnAppenders(event);
    }

    return;
  }

  // Set the NDC and thread name for the calling thread as these
  // LoggingEvent fields were not set at event creation time.
  event.getNDC();
  event.getThreadName();
  // Get a copy of this thread's MDC.
  event.getMDCCopy();
  if (locationInfo) {
    event.getLocationInformation();
  }

  synchronized (buffer) {
    while (true) {
      int previousSize = buffer.size();

      if (previousSize < bufferSize) {
        buffer.add(event);

        //
        //   if buffer had been empty
        //       signal all threads waiting on buffer
        //       to check their conditions.
        //
        if (previousSize == 0) {
          buffer.notifyAll();
        }

        break;
      }

      //
      //   Following code is only reachable if buffer is full
      //
      //
      //   if blocking and thread is not already interrupted
      //      and not the dispatcher then
      //      wait for a buffer notification
      boolean discard = true;
      if (blocking
              && !Thread.interrupted()
              && Thread.currentThread() != dispatcher) {
        try {
          buffer.wait();
          discard = false;
        } catch (InterruptedException e) {
          //
          //  reset interrupt status so
          //    calling code can see interrupt on
          //    their next wait or sleep.
          Thread.currentThread().interrupt();
        }
      }

      //
      //   if blocking is false or thread has been interrupted
      //   add event to discard map.
      //
      if (discard) {
        String loggerName = event.getLoggerName();
        DiscardSummary summary = (DiscardSummary) discardMap.get(loggerName);

        if (summary == null) {
          summary = new DiscardSummary(event);
          discardMap.put(loggerName, summary);
        } else {
          summary.add(event);
        }

        break;
      }
    }
  }
}
 
Example 15
Source File: HTMLLayout.java    From cacheonix-core with GNU Lesser General Public License v2.1 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>");
  sbuf.append(event.timeStamp - LoggingEvent.getStartTime());
  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\">");
  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();
}
 
Example 16
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 17
Source File: StreamAppender.java    From samza with Apache License 2.0 4 votes vote down vote up
private LoggingEvent subLog(LoggingEvent event) {
  return new LoggingEvent(event.getFQNOfLoggerClass(), event.getLogger(), event.getTimeStamp(),
      event.getLevel(), subAppend(event), event.getThreadName(), event.getThrowableInformation(),
      event.getNDC(), event.getLocationInformation(), event.getProperties());
}
 
Example 18
Source File: LoggingEventJsonSerde.java    From samza with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}
 
Example 19
Source File: GlogLayout.java    From xio with Apache License 2.0 4 votes vote down vote up
@Override
public String getClassName(LoggingEvent record) {
  LocationInfo locationInformation = record.getLocationInformation();
  return (locationInformation != null) ? locationInformation.getClassName() : null;
}
 
Example 20
Source File: GlogLayout.java    From xio with Apache License 2.0 4 votes vote down vote up
@Override
public String getMethodName(LoggingEvent record) {
  LocationInfo locationInformation = record.getLocationInformation();
  return (locationInformation != null) ? record.getLocationInformation().getMethodName() : null;
}