Java Code Examples for ch.qos.logback.classic.spi.ILoggingEvent#getFormattedMessage()

The following examples show how to use ch.qos.logback.classic.spi.ILoggingEvent#getFormattedMessage() . 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: DingTalkAppender.java    From jframework with Apache License 2.0 6 votes vote down vote up
private String transformStackTrace(ILoggingEvent event) {
    String exception = "";
    IThrowableProxy throwableProxy =  event.getThrowableProxy();
    if (throwableProxy != null) {
        exception = ThrowableProxyUtil.asString(throwableProxy);
    }

    StackTraceElement[] callerData = event.getCallerData();
    StackTraceElement stackTraceElement = callerData[0];

    String time = DEFAULT_DATE_FORMAT.format(new Date(event.getTimeStamp()));
    String threadName = event.getThreadName();
    String level = event.getLevel().toString();
    String logger = event.getLoggerName();
    String msg = event.getFormattedMessage();
    String className = stackTraceElement.getClassName();
    String method = stackTraceElement.getMethodName();
    int lineNumber = stackTraceElement.getLineNumber();

    return String.format(FORMAT_MESSAGE, time, threadName, level, logger, className, method, lineNumber, exception, msg);
}
 
Example 2
Source File: FlumeLogstashV1Appender.java    From logback-flume-appender with MIT License 6 votes vote down vote up
@Override
protected void append(ILoggingEvent eventObject) {

  if (flumeManager != null) {
    try {
      String body = layout != null ? layout.doLayout(eventObject) : eventObject.getFormattedMessage();
      Map<String, String> headers = new HashMap<String, String>();
      if(additionalAvroHeaders != null) {
        headers.putAll(additionalAvroHeaders);
      }
      headers.putAll(extractHeaders(eventObject));

      Event event = EventBuilder.withBody(StringUtils.strip(body), UTF_8, headers);

      flumeManager.send(event);
    } catch (Exception e) {
      addError(e.getLocalizedMessage(), e);
    }
  }

}
 
Example 3
Source File: JobMessageLogAppender.java    From edison-microservice with Apache License 2.0 6 votes vote down vote up
@Override
protected void append(final ILoggingEvent eventObject) {
    Map<String, String> mdcMap = eventObject.getMDCPropertyMap();
    // TODO: check for JOB marker:
    if (mdcMap.containsKey("job_id") && eventObject.getMarker() != null && JobMarker.JOB.contains(eventObject.getMarker())) {
        String jobId = mdcMap.get("job_id");
        Level level = eventObject.getLevel();
        de.otto.edison.jobs.domain.Level edisonLevel = logLevelToEdisonLevel(level);

        String message = eventObject.getFormattedMessage();

        try {
            final JobMessage jobMessage = jobMessage(edisonLevel, message, OffsetDateTime.now());
            jobService.appendMessage(jobId, jobMessage);
        }
        catch(final RuntimeException e) {
            addError("Failed to persist job message (jobId=" + jobId + "): " + message, e);
        }
    }
}
 
Example 4
Source File: LogViewController.java    From TerasologyLauncher with Apache License 2.0 5 votes vote down vote up
@Override
protected void append(ILoggingEvent loggingEvent) {
    final String message = loggingEvent.getFormattedMessage();
    final LocalDateTime timestamp = timestampFromEvent(loggingEvent);

    buffer.append(String.format("%s | %-5s | ", DATE_FORMATTER.format(timestamp), loggingEvent.getLevel()));
    buffer.append(message);
    buffer.append("\n");
}
 
Example 5
Source File: UKeFuAppender.java    From youkefu with Apache License 2.0 5 votes vote down vote up
@Override
public void append(ILoggingEvent event) {
	super.append(event);
	try {
		if(UKDataContext.getContext()!=null) {
			Log log = new Log(UKDataContext.SYSTEM_ORGI , null , event.getFormattedMessage() , event.getLevel().toString() , event.getThreadName());
			log.setClazz(event.getLoggerName()) ;
			if(event.getFormattedMessage()!=null && event.getFormattedMessage().length() < 255){
				log.setMemo(event.getFormattedMessage());
			}else{
				log.setMemo(event.getFormattedMessage().substring(0 ,255));
			}
			if(event.getThrowableProxy()!=null){
				log.setMsg(ThrowableProxyUtil.asString(event.getThrowableProxy()));
			}
			
			log.setMethod(event.getThreadName());
			log.setLogtype(event.getLevel().toString().equals(Level.ERROR.toString()) ? "1" : "0") ;
			log.setLogtime(String.valueOf(UKTools.dateFormate.format(new Date()))) ;
			/**
			 * 临时缓存
			 */
			UKDataContext.tempLogQueue.add(log) ;
		}
	} catch (Throwable sqle) {
		sqle.printStackTrace();
	}

}
 
Example 6
Source File: TestFileSystemRepository.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testMinimalArchiveCleanupIntervalHonoredAndLogged() throws Exception {
    // We are going to construct our own repository using different properties, so
    // we need to shutdown the existing one.
    shutdown();

    Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    ListAppender<ILoggingEvent> testAppender = new ListAppender<>();
    testAppender.setName("Test");
    testAppender.start();
    root.addAppender(testAppender);
    final Map<String, String> addProps = new HashMap<>();
    addProps.put(NiFiProperties.CONTENT_ARCHIVE_CLEANUP_FREQUENCY, "1 millis");
    final NiFiProperties localProps = NiFiProperties.createBasicNiFiProperties(TestFileSystemRepository.class.getResource("/conf/nifi.properties").getFile(), addProps);
    repository = new FileSystemRepository(localProps);
    repository.initialize(new StandardResourceClaimManager());
    repository.purge();

    boolean messageFound = false;
    String message = "The value of nifi.content.repository.archive.cleanup.frequency property "
            + "is set to '1 millis' which is below the allowed minimum of 1 second (1000 milliseconds). "
            + "Minimum value of 1 sec will be used as scheduling interval for archive cleanup task.";

    // Must synchronize on testAppender, because the call to append() is synchronized and this synchronize
    // keyword guards testAppender.list. Since we are accessing testAppender.list, we must do so in a thread-safe manner.
    synchronized (testAppender) {
        for (ILoggingEvent event : testAppender.list) {
            String actualMessage = event.getFormattedMessage();
            if (actualMessage.equals(message)) {
                assertEquals(event.getLevel(), Level.WARN);
                messageFound = true;
                break;
            }
        }
    }

    assertTrue(messageFound);
}
 
Example 7
Source File: StructuredLoggingEncoder.java    From flo with Apache License 2.0 5 votes vote down vote up
private byte[] encodeStructured(ILoggingEvent event) {
  final StructuredLogMessageBuilder structuredLogMessageBuilder =
      StructuredLogMessage.newBuilder();

  // Standard fields
  structuredLogMessageBuilder.time(Instant.ofEpochMilli(event.getTimeStamp()).toString());
  structuredLogMessageBuilder.severity(event.getLevel().toString());
  structuredLogMessageBuilder.logger(event.getLoggerName());
  structuredLogMessageBuilder.thread(event.getThreadName());
  final StringBuilder message = new StringBuilder(event.getFormattedMessage());
  final IThrowableProxy t = event.getThrowableProxy();
  if (t != null) {
    message.append('\n');
    writeStack(message, t, "", 0, "\n");
  }
  structuredLogMessageBuilder.message(message.toString());

  // Workflow metadata
  final WorkflowBuilder workflowBuilder = StructuredLogMessage.Workflow.newBuilder()
      .styx(template.build());
  final TaskId taskId = taskId();
  workflowBuilder.task(StructuredLogMessage.Task.newBuilder()
      .id(taskId != null ? taskId.toString() : "")
      .name(taskId != null ? taskId.name() : "")
      .args(taskId != null ? taskId.args() : "")
      .build());
  structuredLogMessageBuilder.workflow(workflowBuilder.build());

  // Serialize to json
  try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
    WRITER.writeValue(baos, structuredLogMessageBuilder.build());
    baos.write(LINE_SEPARATOR_BYTES);
    return baos.toByteArray();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 8
Source File: LogbackLoggingConfigurer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected void append(ILoggingEvent event) {
    try {
        ThrowableProxy throwableProxy = (ThrowableProxy) event.getThrowableProxy();
        Throwable throwable = throwableProxy == null ? null : throwableProxy.getThrowable();
        String message = event.getFormattedMessage();
        LogLevel level = LogLevelConverter.toGradleLogLevel(event.getLevel(), event.getMarker());
        outputEventListener.onOutput(new LogEvent(event.getTimeStamp(), event.getLoggerName(), level, message, throwable));
    } catch (Throwable t) {
        // fall back to standard out
        t.printStackTrace(defaultStandardOut);
    }
}
 
Example 9
Source File: LogbackLoggingConfigurer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected void append(ILoggingEvent event) {
    try {
        ThrowableProxy throwableProxy = (ThrowableProxy) event.getThrowableProxy();
        Throwable throwable = throwableProxy == null ? null : throwableProxy.getThrowable();
        String message = event.getFormattedMessage();
        LogLevel level = LogLevelConverter.toGradleLogLevel(event.getLevel(), event.getMarker());
        outputEventListener.onOutput(new LogEvent(event.getTimeStamp(), event.getLoggerName(), level, message, throwable));
    } catch (Throwable t) {
        // fall back to standard out
        t.printStackTrace(defaultStandardOut);
    }
}
 
Example 10
Source File: SLF4JLoggerIT.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
@Override
public void append(ILoggingEvent event)
{
  // Assign the log message and it's level to the outer class instance
  // variables so that it can see the messages logged
  lastLogMessage = event.getFormattedMessage();
  lastLogMessageLevel = event.getLevel();
}
 
Example 11
Source File: CloudwatchLogsLogbackAppender.java    From cloudwatchlogs-java-appender with Apache License 2.0 5 votes vote down vote up
@Override
protected void append(ILoggingEvent event) {
    StringBuilder message = new StringBuilder(event.getFormattedMessage());
    IThrowableProxy throwableProxy = event.getThrowableProxy();
    while (throwableProxy != null) {
        message.append("\n").append(dump(throwableProxy));
        throwableProxy = throwableProxy.getCause();
        if (throwableProxy != null) {
            message.append("\nCaused by:");
        }
    }

    String account = event.getMDCPropertyMap().get(CloudwatchLogsMDCPropertyNames.ACCOUNT);
    String action = event.getMDCPropertyMap().get(CloudwatchLogsMDCPropertyNames.ACTION);
    String user = event.getMDCPropertyMap().get(CloudwatchLogsMDCPropertyNames.USER);
    String session = event.getMDCPropertyMap().get(CloudwatchLogsMDCPropertyNames.SESSION);
    String request = event.getMDCPropertyMap().get(CloudwatchLogsMDCPropertyNames.REQUEST);

    Marker marker = event.getMarker();
    String eventId = marker == null ? null : marker.getName();

    Map<String, String> customMdcAttributes = new HashMap<>();
    for (String key : config.getCustomMdcKeys()) {
        String value = event.getMDCPropertyMap().get(key);
        if (value != null) {
            customMdcAttributes.put(key, value);
        }
    }

    CloudwatchLogsLogEvent logEvent = new CloudwatchLogsLogEvent(event.getLevel().toString(), event.getLoggerName(),
            eventId, message.toString(), event.getTimeStamp(), event.getThreadName(), account, action, user,
            session, request, customMdcAttributes);
    while (!eventQueue.offer(logEvent)) {
        // Discard old logging messages while queue is full.
        eventQueue.poll();
        discardedCount.incrementAndGet();
    }
    processedCount.incrementAndGet();
}
 
Example 12
Source File: ErrorCatcher.java    From FlareBot with MIT License 5 votes vote down vote up
@Override
public FilterReply decide(ILoggingEvent event) {
    String msg = event.getFormattedMessage();
    if (msg == null)
        msg = "null";
    if (event.getMarker() != Markers.NO_ANNOUNCE
            && FlareBot.instance() != null
            && event.getLevel() == Level.ERROR || event.getLevel() == Level.WARN) {
        String finalMsg = msg;
        if (event.getThreadName().startsWith("lava-daemon-pool")) {
            return FilterReply.NEUTRAL;
        }
        EXECUTOR.submit(() -> {
            Throwable throwable = null;
            if (event.getThrowableProxy() != null && event.getThrowableProxy() instanceof ThrowableProxy) {
                throwable = ((ThrowableProxy) event.getThrowableProxy()).getThrowable();
            }
            if (event.getLevel() == Level.WARN) {
                // Warnings should not have a throwable!
                MessageUtils.sendWarningMessage(finalMsg, Constants.getErrorLogChannel());
                return;
            }
            if (throwable != null) {
                if (event.getMarker() == Markers.TAG_DEVELOPER)
                    MessageUtils.sendFatalException(finalMsg, throwable, Constants.getErrorLogChannel());
                else
                    MessageUtils.sendException(finalMsg, throwable, Constants.getErrorLogChannel());
            } else {
                if (event.getMarker() == Markers.TAG_DEVELOPER)
                    MessageUtils.sendFatalErrorMessage(finalMsg, Constants.getErrorLogChannel());
                else
                    MessageUtils.sendErrorMessage(finalMsg, Constants.getErrorLogChannel());
            }
        });
    }
    return FilterReply.NEUTRAL;
}
 
Example 13
Source File: MessageFormatter.java    From UserCenter with MIT License 5 votes vote down vote up
@Override
public String format(ILoggingEvent event) {
    if (event.getFormattedMessage().startsWith(Constant.USER_LOG)) {
        return event.getLevel().toString() + Constant.SPLIT + event.getFormattedMessage();
    } else {
        return null;
    }
}
 
Example 14
Source File: TestFileSystemRepository.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testMinimalArchiveCleanupIntervalHonoredAndLogged() throws Exception {
    // We are going to construct our own repository using different properties, so
    // we need to shutdown the existing one.
    shutdown();

    Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    ListAppender<ILoggingEvent> testAppender = new ListAppender<>();
    testAppender.setName("Test");
    testAppender.start();
    root.addAppender(testAppender);
    final Map<String, String> addProps = new HashMap<>();
    addProps.put(NiFiProperties.CONTENT_ARCHIVE_CLEANUP_FREQUENCY, "1 millis");
    final NiFiProperties localProps = NiFiProperties.createBasicNiFiProperties(null, addProps);
    repository = new FileSystemRepository(localProps);
    repository.initialize(new StandardResourceClaimManager());
    repository.purge();

    boolean messageFound = false;
    String message = "The value of nifi.content.repository.archive.cleanup.frequency property "
            + "is set to '1 millis' which is below the allowed minimum of 1 second (1000 milliseconds). "
            + "Minimum value of 1 sec will be used as scheduling interval for archive cleanup task.";
    for (ILoggingEvent event : testAppender.list) {
        String actualMessage = event.getFormattedMessage();
        if (actualMessage.equals(message)) {
            assertEquals(event.getLevel(), Level.WARN);
            messageFound = true;
            break;
        }
    }
    assertTrue(messageFound);
}
 
Example 15
Source File: LogbackLoggingConfigurer.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected void append(ILoggingEvent event) {
    try {
        ThrowableProxy throwableProxy = (ThrowableProxy) event.getThrowableProxy();
        Throwable throwable = throwableProxy == null ? null : throwableProxy.getThrowable();
        String message = event.getFormattedMessage();
        LogLevel level = LogLevelConverter.toGradleLogLevel(event.getLevel(), event.getMarker());
        outputEventListener.onOutput(new LogEvent(event.getTimeStamp(), event.getLoggerName(), level, message, throwable));
    } catch (Throwable t) {
        // fall back to standard out
        t.printStackTrace(defaultStandardOut);
    }
}
 
Example 16
Source File: LogbackLoggingConfigurer.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected void append(ILoggingEvent event) {
    try {
        ThrowableProxy throwableProxy = (ThrowableProxy) event.getThrowableProxy();
        Throwable throwable = throwableProxy == null ? null : throwableProxy.getThrowable();
        String message = event.getFormattedMessage();
        LogLevel level = LogLevelConverter.toGradleLogLevel(event.getLevel(), event.getMarker());
        outputEventListener.onOutput(new LogEvent(event.getTimeStamp(), event.getLoggerName(), level, message, throwable));
    } catch (Throwable t) {
        // fall back to standard out
        t.printStackTrace(defaultStandardOut);
    }
}
 
Example 17
Source File: StringAppender.java    From spring-boot-data-geode with Apache License 2.0 4 votes vote down vote up
protected String toString(ILoggingEvent loggingEvent) {
	return loggingEvent != null ? loggingEvent.getFormattedMessage() : null;
}
 
Example 18
Source File: MessageFormatter.java    From log_to_kafka with MIT License 4 votes vote down vote up
public String format(ILoggingEvent event) {
    return event.getFormattedMessage();
}
 
Example 19
Source File: MessageFormatter.java    From newblog with Apache License 2.0 4 votes vote down vote up
@Override
public String format(ILoggingEvent event) {
    return event.getFormattedMessage();
}
 
Example 20
Source File: TableViewLogAppender.java    From AsciidocFX with Apache License 2.0 4 votes vote down vote up
@Override
protected void append(ILoggingEvent event) {

    if (Objects.isNull(logViewer))
        return;

    String message = event.getFormattedMessage();
    String level = event.getLevel().toString();

    if (Objects.isNull(message)) {
        return;
    }

    if (event.getLevel() == Level.ERROR) {
        ObservableList<String> styleClass = logShowHider.getStyleClass();
        if (!styleClass.contains("red-label")) {
            styleClass.add("red-label");
        }
    }

    final String finalMessage = message;
    threadService.buff("logMessager").schedule(() -> {
        threadService.runActionLater(() -> {
            logShortMessage.setText(finalMessage);
        });
    }, 1, TimeUnit.SECONDS);


    IThrowableProxy tp = event.getThrowableProxy();
    if (Objects.nonNull(tp) && event.getLevel() == Level.ERROR) {
        String tpMessage = ThrowableProxyUtil.asString(tp);
        message += "\n" + tpMessage;
    }

    if (!message.isEmpty()) {
        MyLog myLog = new MyLog(level, message);
        buffer.add(myLog);
    }

    threadService.buff("logAppender").schedule(() -> {
        final List<MyLog> clone = new LinkedList<>(buffer);
        buffer.clear();
        threadService.runActionLater(() -> {
            logList.addAll(clone);
        });
    }, 2, TimeUnit.SECONDS);
}