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

The following examples show how to use ch.qos.logback.classic.spi.ILoggingEvent#getMarker() . 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: MaskingConverter.java    From owasp-security-logging with Apache License 2.0 6 votes vote down vote up
@Override
public String convert(ILoggingEvent event) {
	Marker eventMarker = event.getMarker();

	Object[] args = event.getArgumentArray();
	if (eventMarker != null
			&& eventMarker.contains(SecurityMarkers.CONFIDENTIAL)) {
		for (int i = 0; i < args.length; i++) {
			args[i] = MASKED_PASSWORD;
		}
	}

	String maskedMessage = MessageFormatter.arrayFormat(event.getMessage(),
			args).getMessage();

	return maskedMessage;
}
 
Example 2
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 3
Source File: GelfEncoder.java    From logback-gelf with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Map<String, Object> mapAdditionalFields(final ILoggingEvent event) {
    final Map<String, Object> additionalFields = new HashMap<>(staticFields);

    additionalFields.put(loggerNameKey, event.getLoggerName());
    additionalFields.put(threadNameKey, event.getThreadName());

    if (includeRawMessage) {
        additionalFields.put("raw_message", event.getMessage());
    }

    if (includeMarker) {
        final Marker marker = event.getMarker();
        if (marker != null) {
            additionalFields.put("marker", buildMarkerStr(marker));
        }
    }

    if (includeLevelName) {
        additionalFields.put(levelNameKey, event.getLevel().levelStr);
    }

    if (includeMdcData) {
        additionalFields.putAll(buildMdcData(event.getMDCPropertyMap()));
    }

    if (includeCallerData) {
        additionalFields.putAll(buildCallerData(event.getCallerData()));
    }

    if (includeRootCauseData) {
        additionalFields.putAll(buildRootExceptionData(event.getThrowableProxy()));
    }

    return additionalFields;
}
 
Example 4
Source File: MarkerFilter.java    From owasp-security-logging with Apache License 2.0 5 votes vote down vote up
public FilterReply decide(ILoggingEvent event) {
	Marker marker = event.getMarker();
	if (!isStarted()) {
		return FilterReply.NEUTRAL;
	}

	if (marker == null) {
		return onMismatch;
	}

	if (markerToMatch.contains(marker)) {
		return onMatch;
	}
	return onMismatch;
}
 
Example 5
Source File: ExcludeClassifiedMarkerFilter.java    From owasp-security-logging with Apache License 2.0 5 votes vote down vote up
public FilterReply decide(ILoggingEvent event) {
	if (!isStarted()) {
		return FilterReply.NEUTRAL;
	}

	// make sure the event has a marker
	Marker eventMarker = event.getMarker();
	if (eventMarker == null) {
		return FilterReply.NEUTRAL;
	}

	if (eventMarker.hasReferences()) {
		// check for events with multiple markers
		for (Marker marker : markersToMatch) {
			if (eventMarker.contains(marker)) {
				return FilterReply.DENY;
			}
		}
	} else {
		// handle simple case of an event with a single marker
		if (markersToMatch.contains(eventMarker)) {
			return FilterReply.DENY;
		}
	}

	// no classified markers found
	return FilterReply.NEUTRAL;
}
 
Example 6
Source File: SecurityMarkerFilter.java    From owasp-security-logging with Apache License 2.0 5 votes vote down vote up
public FilterReply decide(ILoggingEvent event) {
	if (!isStarted()) {
		return FilterReply.NEUTRAL;
	}

	// make sure the event has a marker
	Marker eventMarker = event.getMarker();

	if (eventMarker == null) {
		return FilterReply.DENY;
	}

	if (eventMarker.hasReferences()) {
		// check for events with multiple markers
		for (Marker marker : markersToMatch) {
			if (eventMarker.contains(marker)) {
				return acceptAll ? FilterReply.ACCEPT : FilterReply.NEUTRAL;
			}
		}
	} else {
		// handle simple case of an event with a single marker
		if (markersToMatch.contains(eventMarker)) {
			return acceptAll ? FilterReply.ACCEPT : FilterReply.NEUTRAL;
		}
	}

	// no match found for security markers
	return FilterReply.DENY;
}
 
Example 7
Source File: RollbarAppender.java    From rollbar-java with MIT License 5 votes vote down vote up
private String getMarker(ILoggingEvent event) {
  if (event.getMarker() == null) {
    return null;
  }

  return event.getMarker().getName();
}
 
Example 8
Source File: LogbackRecorder.java    From jhipster with Apache License 2.0 5 votes vote down vote up
Event(ILoggingEvent event) {
    this.marker = event.getMarker();
    this.level = event.getLevel().toString();
    this.message = event.getMessage();
    this.arguments = event.getArgumentArray();
    final IThrowableProxy proxy = event.getThrowableProxy();
    this.thrown = proxy == null ? null : proxy.getClassName() + ": " + proxy.getMessage();
}
 
Example 9
Source File: JsonEncoder.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
private Marker getMarker(ILoggingEvent event) {
	if (hasException(event)) {
		return Markers.EXCEPTION_MARKER;
	}
	Marker m = event.getMarker();
	if (m == null) {
		m = Markers.DEFAULT_MARKER;
	}
	return m;
}
 
Example 10
Source File: EcsEncoder.java    From ecs-logging-java with Apache License 2.0 5 votes vote down vote up
private void serializeMarkers(ILoggingEvent event, StringBuilder builder) {
    Marker marker = event.getMarker();
    if (includeMarkers && marker != null) {
        EcsJsonSerializer.serializeTagStart(builder);
        serializeMarker(builder, marker);
        EcsJsonSerializer.serializeTagEnd(builder);
    }
}
 
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: MetricBlockFilter.java    From lambda-monitoring with Apache License 2.0 5 votes vote down vote up
@Override
public FilterReply decide(ILoggingEvent event) {
    Marker eventMarker = event.getMarker();
    if (isStarted() && eventMarker != null && eventMarker.contains(MetricPassFilter.METRIC_MARKER)) {
        return FilterReply.DENY;
    }
    return FilterReply.NEUTRAL;
}
 
Example 13
Source File: MetricPassFilter.java    From lambda-monitoring with Apache License 2.0 5 votes vote down vote up
@Override
public FilterReply decide(ILoggingEvent event) {
    Marker eventMarker = event.getMarker();
    if (isStarted() && (eventMarker == null || !eventMarker.contains(METRIC_MARKER))) {
        return FilterReply.DENY;
    } else {
        return FilterReply.NEUTRAL;
    }
}
 
Example 14
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 15
Source File: MarkerFilter.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public FilterReply decide(ILoggingEvent event) {
  if (!isStarted()) {
    return FilterReply.NEUTRAL;
  }

  Marker currentMarker = event.getMarker();

  if (currentMarker == null || !marker.equals(currentMarker.getName())) {
    return onMismatch;
  } else {
    return onMatch;
  }
}
 
Example 16
Source File: LogzioLogbackAppender.java    From logzio-logback-appender with Apache License 2.0 4 votes vote down vote up
private JsonObject formatMessageAsJsonInternal(ILoggingEvent loggingEvent) {
    JsonObject logMessage;

    if (format.equals(FORMAT_JSON)) {
        try {
            JsonElement jsonElement = gson.fromJson(loggingEvent.getFormattedMessage(), JsonElement.class);
            logMessage = jsonElement.getAsJsonObject();
        } catch (Exception e) {
            logMessage = new JsonObject();
            logMessage.addProperty(MESSAGE, loggingEvent.getFormattedMessage());
        }
    } else {
        logMessage = new JsonObject();
        logMessage.addProperty(MESSAGE, loggingEvent.getFormattedMessage());
    }

    // Adding MDC first, as I dont want it to collide with any one of the following fields
    if (loggingEvent.getMDCPropertyMap() != null) {
        loggingEvent.getMDCPropertyMap().forEach(logMessage::addProperty);
    }

    logMessage.addProperty(TIMESTAMP, new Date(loggingEvent.getTimeStamp()).toInstant().toString());
    logMessage.addProperty(LOGLEVEL,loggingEvent.getLevel().levelStr);

    if (loggingEvent.getMarker() != null) {
        logMessage.addProperty(MARKER, loggingEvent.getMarker().toString());
    }

    logMessage.addProperty(LOGGER, loggingEvent.getLoggerName());
    logMessage.addProperty(THREAD, loggingEvent.getThreadName());
    if (line) {
        logMessage.addProperty(LINE, lineOfCallerConverter.convert(loggingEvent));
    }

    if (loggingEvent.getThrowableProxy() != null) {
        logMessage.addProperty(EXCEPTION, throwableProxyConverter.convert(loggingEvent));
    }

    if (additionalFieldsMap != null) {
        additionalFieldsMap.forEach(logMessage::addProperty);
    }

    return logMessage;
}
 
Example 17
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");
    }
}
 
Example 18
Source File: Filter.java    From FlareBot with MIT License 4 votes vote down vote up
@Override
public FilterReply decide(ILoggingEvent event) {
    if (event.getMarker() == Markers.NO_ANNOUNCE) return FilterReply.DENY;
    return FilterReply.NEUTRAL;
}
 
Example 19
Source File: LogbackQiniuAppender.java    From qiniu-logging-plugin with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected void append(ILoggingEvent logEvent) {
    Point point = new Point();
    point.append("timestamp", logEvent.getTimeStamp());
    point.append("level", logEvent.getLevel().toString());
    point.append("logger", logEvent.getLoggerName());

    if (logEvent.getMarker() != null) {
        point.append("marker", logEvent.getMarker().toString());
    } else {
        point.append("marker", "");
    }

    point.append("message", logEvent.getMessage());
    point.append("thread_name", logEvent.getThreadName());
    point.append("thread_id", 0); // logback doest not support thread id
    point.append("thread_priority", 0);
    if (logEvent.getThrowableProxy() != null) {
        StringBuilder exceptionBuilder = new StringBuilder();
        exceptionBuilder.append(logEvent.getThrowableProxy().getMessage()).append("\n");
        for (StackTraceElementProxy proxy : logEvent.getThrowableProxy().getStackTraceElementProxyArray()) {
            exceptionBuilder.append(proxy.getStackTraceElement().toString()).append("\n");
        }
        point.append("exception", exceptionBuilder.toString());
    } else {
        point.append("exception", "");
    }

    //lock
    this.rwLock.lock();
    if (!batch.canAdd(point)) {

        final byte[] postBody = batch.toString().getBytes(Constants.UTF_8);
        try {
            this.executorService.execute(new Runnable() {
                public void run() {
                    try {
                        Response response = logPushSender.send(postBody);
                        response.close();
                    } catch (QiniuException e) {
                        //e.printStackTrace();
                        guard.write(postBody);
                    }
                }
            });
        } catch (RejectedExecutionException ex) {
            guard.write(postBody);
        }

        batch.clear();
    }
    batch.add(point);
    this.rwLock.unlock();
}
 
Example 20
Source File: BugsnagAppender.java    From bugsnag-java with MIT License 4 votes vote down vote up
@Override
protected void append(final ILoggingEvent event) {
    if (bugsnag != null) {
        Throwable throwable = extractThrowable(event);

        final Callback reportCallback;
        Marker marker = event.getMarker();
        if (marker instanceof BugsnagMarker) {
            reportCallback = ((BugsnagMarker) marker).getCallback();
        } else {
            reportCallback = null;
        }

        // Only send a message if there is an exception, the log does not come
        // from the this library and the logger is not in the list of excluded loggers.
        if (throwable != null
                && !detectLogFromBugsnag(throwable)
                && !isExcludedLogger(event.getLoggerName())) {
            bugsnag.notify(
                    throwable,
                    calculateSeverity(event),
                    new Callback() {
                        @Override
                        public void beforeNotify(Report report) {

                            // Add some data from the logging event
                            report.addToTab("Log event data",
                                    "Message", event.getMessage());
                            report.addToTab("Log event data",
                                    "Logger name", event.getLoggerName());

                            // Add details from the logging context to the event
                            populateContextData(report, event);

                            if (reportCallback != null) {
                                reportCallback.beforeNotify(report);
                            }
                        }
                    });
        }
    }
}