Java Code Examples for ch.qos.logback.classic.spi.LoggingEvent#setTimeStamp()

The following examples show how to use ch.qos.logback.classic.spi.LoggingEvent#setTimeStamp() . 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: CustomGelfEncoderTest.java    From logback-gelf with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void custom() throws IOException {
    encoder.start();

    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    final Logger logger = lc.getLogger(LOGGER_NAME);

    final LoggingEvent event = simpleLoggingEvent(logger, null);
    event.setTimeStamp(TIMESTAMP);
    event.setThreadName(THREAD_NAME);
    final String logMsg = encodeToStr(event);

    final ObjectMapper om = new ObjectMapper();
    final JsonNode jsonNode = om.readTree(logMsg);
    basicValidation(jsonNode);

    assertEquals("message 1\n", jsonNode.get("full_message").textValue());
    assertEquals(
        "ad4ab384b5b7dca879dc1b65132db321a67239f13c2cc0cd9867c8e607c7ce08",
        jsonNode.get("_sha256").textValue(),
        "Log line: " + logMsg
    );
}
 
Example 2
Source File: CloudWatchAppender.java    From cloudwatch-logback-appender with ISC License 5 votes vote down vote up
private LoggingEvent makeEvent(Level level, String message, Throwable th) {
	LoggingEvent event = new LoggingEvent();
	event.setLoggerName(CloudWatchAppender.class.getName());
	event.setLevel(level);
	event.setMessage(message);
	event.setTimeStamp(System.currentTimeMillis());
	if (th != null) {
		event.setThrowableProxy(new ThrowableProxy(th));
	}
	return event;
}
 
Example 3
Source File: YarnTwillLogHandler.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public void onLog(LogEntry logEntry) {

  final LoggingEvent loggingEvent = new LoggingEvent();
  loggingEvent.setTimeStamp(logEntry.getTimestamp());
  loggingEvent.setLoggerName(logEntry.getLoggerName());
  loggingEvent.setLevel(Level.valueOf(logEntry.getLogLevel().name()));
  loggingEvent.setThreadName(logEntry.getThreadName());
  Object [] formatObjects = new Object[] {logEntry.getHost(),
    getSimpleClassName(logEntry.getSourceClassName()),
    logEntry.getSourceMethodName(),
    logEntry.getFileName(),
    logEntry.getLineNumber(),logEntry.getMessage()};
  loggingEvent.setMessage(MESSAGE_FORMAT.get().format(formatObjects));

  // Prints the throwable and stack trace.
  LogThrowable logThrowable = logEntry.getThrowable();
  if (logThrowable != null) {
    loggingEvent.setThrowableProxy(new ThrowableProxy(setThrowable(logThrowable)));
  }

  if (logger instanceof Logger) {
    ((Logger) logger).callAppenders(loggingEvent);
  } else {
    logger.info("Logger is not instance of ch.qos.logback.classic.Logger. Logger event is: {}", loggingEvent);
  }
}
 
Example 4
Source File: CloudWatchAppenderTest.java    From cloudwatch-logback-appender with ISC License 4 votes vote down vote up
@Test(timeout = 5000)
public void testBasic() throws InterruptedException {
	CloudWatchAppender appender = new CloudWatchAppender();
	AWSLogsClient awsLogClient = createMock(AWSLogsClient.class);
	appender.setAwsLogsClient(awsLogClient);

	appender.setMaxBatchSize(1);
	appender.setRegion("region");
	final String logGroup = "pfqoejpfqe";
	appender.setLogGroup(logGroup);
	final String logStream = "pffqjfqjpoqoejpfqe";
	appender.setLogStream(logStream);
	PatternLayout layout = new PatternLayout();
	layout.setContext(new LoggerContext());
	layout.setPattern("[%thread] %level %logger{20} - %msg%n%xThrowable");
	layout.start();
	appender.setLayout(layout);

	LoggingEvent event = new LoggingEvent();
	event.setTimeStamp(System.currentTimeMillis());
	String loggerName = "name";
	event.setLoggerName(loggerName);
	Level level = Level.DEBUG;
	event.setLevel(level);
	String message = "fjpewjfpewjfpewjfepowf";
	event.setMessage(message);

	String threadName = Thread.currentThread().getName();
	final String fullMessage = "[" + threadName + "] " + level + " " + loggerName + " - " + message + "\n";

	final PutLogEventsResult result = new PutLogEventsResult();
	String sequence = "ewopjfewfj";
	result.setNextSequenceToken(sequence);
	expect(awsLogClient.putLogEvents(isA(PutLogEventsRequest.class))).andAnswer(new IAnswer<PutLogEventsResult>() {
		@Override
		public PutLogEventsResult answer() {
			PutLogEventsRequest request = (PutLogEventsRequest) getCurrentArguments()[0];
			assertEquals(logGroup, request.getLogGroupName());
			assertEquals(logStream, request.getLogStreamName());
			List<InputLogEvent> events = request.getLogEvents();
			assertEquals(1, events.size());
			assertEquals(fullMessage, events.get(0).getMessage());
			return result;
		}
	}).times(2);
	awsLogClient.shutdown();

	// =====================================

	replay(awsLogClient);
	appender.start();
	// for coverage
	appender.start();
	appender.append(event);
	Thread.sleep(10);
	appender.append(event);
	while (appender.getEventsWrittenCount() < 2) {
		Thread.sleep(10);
	}
	appender.stop();
	verify(awsLogClient);
}
 
Example 5
Source File: CloudWatchAppenderTest.java    From cloudwatch-logback-appender with ISC License 4 votes vote down vote up
@Test(timeout = 5000)
public void testInstanceName() throws InterruptedException {
	CloudWatchAppender appender = new CloudWatchAppender();
	AWSLogsClient awsLogClient = createMock(AWSLogsClient.class);
	appender.setAwsLogsClient(awsLogClient);

	appender.setMaxBatchSize(1);
	appender.setRegion("region");
	final String logGroup = "pfqoejpfqe";
	appender.setLogGroup(logGroup);
	String prefix = "logstream-";
	appender.setLogStream(prefix + "%instanceName");
	final String expectedLogStream = prefix + "unknown";
	PatternLayout layout = new PatternLayout();
	layout.setPattern("%msg");
	layout.start();
	appender.setLayout(layout);

	LoggingEvent event = new LoggingEvent();
	event.setTimeStamp(System.currentTimeMillis());
	event.setLoggerName("name");
	event.setLevel(Level.DEBUG);
	event.setMessage("message");

	final PutLogEventsResult result = new PutLogEventsResult();
	result.setNextSequenceToken("ewopjfewfj");
	expect(awsLogClient.putLogEvents(isA(PutLogEventsRequest.class))).andAnswer(new IAnswer<PutLogEventsResult>() {
		@Override
		public PutLogEventsResult answer() {
			PutLogEventsRequest request = (PutLogEventsRequest) getCurrentArguments()[0];
			assertEquals(logGroup, request.getLogGroupName());
			assertEquals(expectedLogStream, request.getLogStreamName());
			return result;
		}
	});
	awsLogClient.shutdown();

	// =====================================

	replay(awsLogClient);
	appender.start();
	appender.append(event);
	while (appender.getEventsWrittenCount() < 1) {
		Thread.sleep(10);
	}
	appender.stop();
	verify(awsLogClient);
}
 
Example 6
Source File: AsyncWorkerTest.java    From logback-awslogs-appender with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static ILoggingEvent dummyEvent() {
    LoggerContext loggerContext = new LoggerContext();
    LoggingEvent event = new LoggingEvent(AsyncWorkerTest.class.getName(), loggerContext.getLogger(AsyncWorkerTest.class.getName()), Level.WARN, "Dummy " + UUID.randomUUID().toString(), null, null);
    event.setTimeStamp(timestamp.getAndIncrement());
    return event;
}
 
Example 7
Source File: GelfAppender.java    From logback-gelf-appender with Apache License 2.0 4 votes vote down vote up
@Override
protected void append(ILoggingEvent event) {

    if (event == null) {
        return;
    }

    // create a copy of the logging event to avoid passing exception stacktraces to GELF's short_message field
    LoggingEvent copy = new LoggingEvent();
    copy.setMessage(event.getMessage());
    copy.setLevel(event.getLevel());
    copy.setArgumentArray(event.getArgumentArray());
    copy.setLoggerName(event.getLoggerName());
    copy.setThreadName(event.getThreadName());
    copy.setTimeStamp(event.getTimeStamp());
    copy.setMDCPropertyMap(event.getMDCPropertyMap());

    final GelfMessageBuilder builder = new GelfMessageBuilder(this.layout.doLayout(copy), hostName).timestamp(
                event.getTimeStamp() / 1000d)
            .level(GelfMessageLevel.fromNumericLevel(toGelfNumericValue(event.getLevel())))
            .additionalField("loggerName", event.getLoggerName())
            .additionalField("threadName", event.getThreadName());

    final Marker marker = event.getMarker();

    if (marker != null) {
        builder.additionalField("marker", marker.getName());
    }

    if (includeMDC) {
        for (Map.Entry<String, String> entry : event.getMDCPropertyMap().entrySet()) {
            builder.additionalField(entry.getKey(), entry.getValue());
        }
    }

    final StackTraceElement[] callerData = event.getCallerData();

    if (includeSource && event.hasCallerData() && callerData.length > 0) {
        StackTraceElement source = callerData[0];

        builder.additionalField("sourceFileName", source.getFileName());
        builder.additionalField("sourceMethodName", source.getMethodName());
        builder.additionalField("sourceClassName", source.getClassName());
        builder.additionalField("sourceLineNumber", source.getLineNumber());
    }

    final IThrowableProxy thrown = event.getThrowableProxy();

    if (includeStackTrace && thrown != null) {
        String convertedThrowable = throwableConverter.convert(event);

        builder.additionalField("exceptionClass", thrown.getClassName());
        builder.additionalField("exceptionMessage", thrown.getMessage());
        builder.additionalField("exceptionStackTrace", convertedThrowable);

        builder.fullMessage(event.getFormattedMessage() + "\n\n" + convertedThrowable);
    } else {
        builder.fullMessage(event.getFormattedMessage());
    }

    if (includeLevelName) {
        builder.additionalField("levelName", event.getLevel().levelStr);
    }

    if (!additionalFields.isEmpty()) {
        builder.additionalFields(additionalFields);
    }

    if(!client.trySend(builder.build())) {
        addError("Failed to write log event to the GELF server using trySend");
    }
}