Java Code Examples for org.apache.logging.log4j.core.LogEvent#getMarker()

The following examples show how to use org.apache.logging.log4j.core.LogEvent#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: MutableLogEvent.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the fields of this {@code MutableLogEvent} from another event.
 * Similar in purpose and usage as {@link org.apache.logging.log4j.core.impl.Log4jLogEvent.LogEventProxy},
 * but a mutable version.
 * <p>
 * This method is used on async logger ringbuffer slots holding MutableLogEvent objects in each slot.
 * </p>
 *
 * @param event the event to copy data from
 */
public void initFrom(final LogEvent event) {
    this.loggerFqcn = event.getLoggerFqcn();
    this.marker = event.getMarker();
    this.level = event.getLevel();
    this.loggerName = event.getLoggerName();
    this.thrown = event.getThrown();
    this.thrownProxy = event.getThrownProxy();

    this.instant.initFrom(event.getInstant());

    // NOTE: this ringbuffer event SHOULD NOT keep a reference to the specified
    // thread-local MutableLogEvent's context data, because then two threads would call
    // ReadOnlyStringMap.clear() on the same shared instance, resulting in data corruption.
    this.contextData.putAll(event.getContextData());

    this.contextStack = event.getContextStack();
    this.source = event.isIncludeLocation() ? event.getSource() : null;
    this.threadId = event.getThreadId();
    this.threadName = event.getThreadName();
    this.threadPriority = event.getThreadPriority();
    this.endOfBatch = event.isEndOfBatch();
    this.includeLocation = event.isIncludeLocation();
    this.nanoTime = event.getNanoTime();
    setMessage(event.getMessage());
}
 
Example 2
Source File: Log4jLogEvent.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
public LogEventProxy(final LogEvent event, final boolean includeLocation) {
    this.loggerFQCN = event.getLoggerFqcn();
    this.marker = event.getMarker();
    this.level = event.getLevel();
    this.loggerName = event.getLoggerName();

    final Message temp = event.getMessage();
    message = temp instanceof ReusableMessage
            ? memento((ReusableMessage) temp)
            : temp;
    this.timeMillis = event.getInstant().getEpochMillisecond();
    this.nanoOfMillisecond = event.getInstant().getNanoOfMillisecond();
    this.thrown = event.getThrown();
    this.thrownProxy = event.getThrownProxy();
    this.contextData = memento(event.getContextData());
    this.contextStack = event.getContextStack();
    this.source = includeLocation ? event.getSource() : null;
    this.threadId = event.getThreadId();
    this.threadName = event.getThreadName();
    this.threadPriority = event.getThreadPriority();
    this.isLocationRequired = includeLocation;
    this.isEndOfBatch = event.isEndOfBatch();
    this.nanoTime = event.getNanoTime();
}
 
Example 3
Source File: EcsLayout.java    From ecs-logging-java with Apache License 2.0 6 votes vote down vote up
private void serializeTags(LogEvent event, StringBuilder builder) {
    List<String> contextStack = event.getContextStack().asList();
    Marker marker = event.getMarker();
    boolean hasTags = !contextStack.isEmpty() || (includeMarkers && marker != null);
    if (hasTags) {
        EcsJsonSerializer.serializeTagStart(builder);
    }

    if (!contextStack.isEmpty()) {
        final int len = contextStack.size();
        for (int i = 0; i < len; i++) {
            builder.append('\"');
            JsonUtils.quoteAsString(contextStack.get(i), builder);
            builder.append("\",");
        }
    }

    if (includeMarkers && marker != null) {
        serializeMarker(builder, marker);
    }

    if (hasTags) {
        EcsJsonSerializer.serializeTagEnd(builder);
    }
}
 
Example 4
Source File: MarkerSimpleNamePatternConverter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void format(final LogEvent event, final StringBuilder toAppendTo) {
    final Marker marker = event.getMarker();
    if (marker != null) {
        toAppendTo.append(marker.getName());
    }
}
 
Example 5
Source File: MarkerPatternSelector.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public PatternFormatter[] getFormatters(final LogEvent event) {
    final Marker marker = event.getMarker();
    if (marker == null) {
        return defaultFormatters;
    }
    for (final String key : formatterMap.keySet()) {
        if (marker.isInstanceOf(key)) {
            return formatterMap.get(key);
        }
    }
    return defaultFormatters;
}
 
Example 6
Source File: EventLookup.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Looks up the value from the logging event.
 * @param event The current LogEvent.
 * @param key  the key to be looked up.
 * @return The value of the specified log event field.
 */
@Override
public String lookup(final LogEvent event, final String key) {
    switch (key) {
        case "Marker": {
            return event.getMarker() != null ? event.getMarker().getName() : null;
        }
        case "ThreadName": {
            return event.getThreadName();
        }
        case "Level": {
            return event.getLevel().toString();
        }
        case "ThreadId": {
            return Long.toString(event.getThreadId());
        }
        case "Timestamp": {
            return Long.toString(event.getTimeMillis());
        }
        case "Exception": {
            if (event.getThrown() != null) {
                return event.getThrown().getClass().getSimpleName();
            }
            if (event.getThrownProxy() != null) {
                return event.getThrownProxy().getName();
            }
            return null;
        }
        case "Logger": {
            return event.getLoggerName();
        }
        case "Message": {
            return event.getMessage().getFormattedMessage();
        }
        default: {
            return null;
        }
    }
}
 
Example 7
Source File: MarkerPatternConverter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void format(final LogEvent event, final StringBuilder toAppendTo) {
    final Marker marker = event.getMarker();
    if (marker != null) {
        StringBuilders.appendValue(toAppendTo, marker);
    }
}
 
Example 8
Source File: ExcludeClassifiedMarkerFilter.java    From owasp-security-logging with Apache License 2.0 5 votes vote down vote up
@Override
public Result filter(LogEvent event) {
	// make sure the event has a marker
	org.apache.logging.log4j.Marker eventMarker = event.getMarker();
	if (eventMarker == null) {
		return Result.NEUTRAL;
	}

	return filter(eventMarker);
}
 
Example 9
Source File: SecurityMarkerFilter.java    From owasp-security-logging with Apache License 2.0 5 votes vote down vote up
@Override
public Result filter(LogEvent event) {
	// make sure the event has a marker
	org.apache.logging.log4j.Marker eventMarker = event.getMarker();
	if (eventMarker == null) {
		return Result.DENY;
	}

	return filter(eventMarker);
}
 
Example 10
Source File: RollbarAppender.java    From rollbar-java with MIT License 5 votes vote down vote up
private String getMarker(LogEvent event) {
  if (event.getMarker() == null) {
    return null;
  }

  return event.getMarker().getName();
}
 
Example 11
Source File: CloudwatchLogsLog4J2Appender.java    From cloudwatchlogs-java-appender with Apache License 2.0 5 votes vote down vote up
@Override
public void append(LogEvent event) {
    StringBuilder message = new StringBuilder(event.getMessage().getFormattedMessage());
    Throwable thrown = event.getThrown();
    while (thrown != null) {
        message.append("\n").append(dump(thrown));
        thrown = thrown.getCause();
        if (thrown != null) {
            message.append("\nCaused by:");
        }
    }

    String account = event.getContextData().getValue(CloudwatchLogsMDCPropertyNames.ACCOUNT);
    String action = event.getContextData().getValue(CloudwatchLogsMDCPropertyNames.ACTION);
    String user = event.getContextData().getValue(CloudwatchLogsMDCPropertyNames.USER);
    String session = event.getContextData().getValue(CloudwatchLogsMDCPropertyNames.SESSION);
    String request = event.getContextData().getValue(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.getContextData().getValue(key);
        if (value != null) {
            customMdcAttributes.put(key, value);
        }
    }

    CloudwatchLogsLogEvent logEvent = new CloudwatchLogsLogEvent(event.getLevel().toString(), event.getLoggerName(),
            eventId, message.toString(), event.getTimeMillis(), event.getThreadName(), account, action, user,
            session, request, customMdcAttributes);
    while (!eventQueue.offer(logEvent)) {
        eventQueue.poll();
        discardedCount++;
    }
}
 
Example 12
Source File: GelfAppender.java    From log4j2-gelf with Apache License 2.0 4 votes vote down vote up
@Override
public void append(LogEvent event) {
    final Layout<? extends Serializable> layout = getLayout();
    final String formattedMessage;
    if (layout == null) {
        formattedMessage = event.getMessage().getFormattedMessage();
    } else {
        formattedMessage = new String(layout.toByteArray(event), StandardCharsets.UTF_8);
    }

    final GelfMessageBuilder builder = new GelfMessageBuilder(formattedMessage, hostName)
            .timestamp(event.getTimeMillis() / 1000d)
            .level(GelfMessageLevel.fromNumericLevel(Severity.getSeverity(event.getLevel()).getCode()))
            .additionalField("loggerName", event.getLoggerName())
            .additionalField("threadName", event.getThreadName());

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

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

        // Guard against https://issues.apache.org/jira/browse/LOG4J2-1530
        final ThreadContext.ContextStack contextStack = event.getContextStack();
        if (contextStack != null) {
            final List<String> contextStackItems = contextStack.asList();
            if (contextStackItems != null && !contextStackItems.isEmpty()) {
                builder.additionalField("contextStack", contextStackItems.toString());
            }
        }
    }

    if (includeSource) {
        final StackTraceElement source = event.getSource();
        if (source != null) {
            builder.additionalField("sourceFileName", source.getFileName());
            builder.additionalField("sourceMethodName", source.getMethodName());
            builder.additionalField("sourceClassName", source.getClassName());
            builder.additionalField("sourceLineNumber", source.getLineNumber());
        }
    }

    @SuppressWarnings("all")
    final Throwable thrown = event.getThrown();
    if (includeStackTrace && thrown != null) {
        String stackTrace;
        if (includeExceptionCause) {
            final StringWriter stringWriter = new StringWriter();
            final PrintWriter printWriter = new PrintWriter(stringWriter);
            thrown.printStackTrace(printWriter);
            stackTrace = stringWriter.toString();
        } else {
            stackTrace = getSimpleStacktraceAsString(thrown);
        }

        builder.additionalField("exceptionClass", thrown.getClass().getCanonicalName());
        builder.additionalField("exceptionMessage", thrown.getMessage());
        builder.additionalField("exceptionStackTrace", stackTrace);

        builder.fullMessage(formattedMessage);
    }

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

    final GelfMessage gelfMessage = builder.build();
    try {
        final boolean sent = client.trySend(gelfMessage);
        if (!sent) {
            LOG.debug("Couldn't send message: {}", gelfMessage);
        }
    } catch (Exception e) {
        throw new AppenderLoggingException("failed to write log event to GELF server: " + e.getMessage(), e);
    }
}
 
Example 13
Source File: MarkerResolver.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isResolvable(final LogEvent logEvent) {
    return logEvent.getMarker() != null;
}
 
Example 14
Source File: MaskingRewritePolicy.java    From owasp-security-logging with Apache License 2.0 4 votes vote down vote up
/**
 * Rewrite the event.
 *
 * @param source a logging event that may be returned or used to create a
 * new logging event.
 * @return The LogEvent after rewriting.
 */
@Override
public LogEvent rewrite(LogEvent source) {
	// get the markers for the log event. If no markers, nothing can be
	// tagged confidential and we can return
	Marker sourceMarker = source.getMarker();
	if (sourceMarker == null) {
		return source;
	}

	// get the message. If no message we can return
	final Message msg = source.getMessage();
	if (msg == null || !(msg instanceof ParameterizedMessage)) {
		return source;
	}

	// get the parameters. If no params we can return
	Object[] params = msg.getParameters();
	if (params == null || params.length == 0) {
		return source;
	}

	// check if this event is actually marked as confidential. If not,
	// return
	Log4jMarker eventMarker = new Log4jMarker(sourceMarker);
	if (!eventMarker.contains(SecurityMarkers.CONFIDENTIAL)) {
		return source;
	}

	// we have a message, parameters, a marker, and it is confidential.
	// Process
	for (int i = 0; i < params.length; i++) {
		params[i] = MASKED_PASSWORD;
	}

	// create new message
	Message outMessage = new ParameterizedMessage(msg.getFormat(), params,
			msg.getThrowable());

	// build new log event for output
	LogEvent output = new Log4jLogEvent.Builder(source)
			.setMessage(outMessage).build();

	return output;
}
 
Example 15
Source File: MarkerLookup.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public String lookup(final LogEvent event, final String key) {
    final Marker marker = event == null ? null : event.getMarker();
    return marker == null ? null : marker.getName();
}
 
Example 16
Source File: Log4jLogEvent.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
public Builder(final LogEvent other) {
    Objects.requireNonNull(other);
    if (other instanceof RingBufferLogEvent) {
        ((RingBufferLogEvent) other).initializeBuilder(this);
        return;
    }
    if (other instanceof MutableLogEvent) {
        ((MutableLogEvent) other).initializeBuilder(this);
        return;
    }
    this.loggerFqcn = other.getLoggerFqcn();
    this.marker = other.getMarker();
    this.level = other.getLevel();
    this.loggerName = other.getLoggerName();
    this.message = other.getMessage();
    this.instant.initFrom(other.getInstant());
    this.thrown = other.getThrown();
    this.contextStack = other.getContextStack();
    this.includeLocation = other.isIncludeLocation();
    this.endOfBatch = other.isEndOfBatch();
    this.nanoTime = other.getNanoTime();

    // Avoid unnecessarily initializing thrownProxy, threadName and source if possible
    if (other instanceof Log4jLogEvent) {
        final Log4jLogEvent evt = (Log4jLogEvent) other;
        this.contextData = evt.contextData;
        this.thrownProxy = evt.thrownProxy;
        this.source = evt.source;
        this.threadId = evt.threadId;
        this.threadName = evt.threadName;
        this.threadPriority = evt.threadPriority;
    } else {
        if (other.getContextData() instanceof StringMap) {
            this.contextData = (StringMap) other.getContextData();
        } else {
            if (this.contextData.isFrozen()) {
                this.contextData = ContextDataFactory.createContextData();
            } else {
                this.contextData.clear();
            }
            this.contextData.putAll(other.getContextData());

        }
        this.thrownProxy = other.getThrownProxy();
        this.source = other.getSource();
        this.threadId = other.getThreadId();
        this.threadName = other.getThreadName();
        this.threadPriority = other.getThreadPriority();
    }
}
 
Example 17
Source File: NoSqlDatabaseManager.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private void setFields(final LogEvent event, final NoSqlObject<W> entity) {
    entity.set("level", event.getLevel());
    entity.set("loggerName", event.getLoggerName());
    entity.set("message", event.getMessage() == null ? null : event.getMessage().getFormattedMessage());

    final StackTraceElement source = event.getSource();
    if (source == null) {
        entity.set("source", (Object) null);
    } else {
        entity.set("source", this.convertStackTraceElement(source));
    }

    final Marker marker = event.getMarker();
    if (marker == null) {
        entity.set("marker", (Object) null);
    } else {
        entity.set("marker", buildMarkerEntity(marker));
    }

    entity.set("threadId", event.getThreadId());
    entity.set("threadName", event.getThreadName());
    entity.set("threadPriority", event.getThreadPriority());
    entity.set("millis", event.getTimeMillis());
    entity.set("date", new java.util.Date(event.getTimeMillis()));

    @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
    Throwable thrown = event.getThrown();
    if (thrown == null) {
        entity.set("thrown", (Object) null);
    } else {
        final NoSqlObject<W> originalExceptionEntity = this.connection.createObject();
        NoSqlObject<W> exceptionEntity = originalExceptionEntity;
        exceptionEntity.set("type", thrown.getClass().getName());
        exceptionEntity.set("message", thrown.getMessage());
        exceptionEntity.set("stackTrace", this.convertStackTrace(thrown.getStackTrace()));
        while (thrown.getCause() != null) {
            thrown = thrown.getCause();
            final NoSqlObject<W> causingExceptionEntity = this.connection.createObject();
            causingExceptionEntity.set("type", thrown.getClass().getName());
            causingExceptionEntity.set("message", thrown.getMessage());
            causingExceptionEntity.set("stackTrace", this.convertStackTrace(thrown.getStackTrace()));
            exceptionEntity.set("cause", causingExceptionEntity);
            exceptionEntity = causingExceptionEntity;
        }

        entity.set("thrown", originalExceptionEntity);
    }

    final ReadOnlyStringMap contextMap = event.getContextData();
    if (contextMap == null) {
        entity.set("contextMap", (Object) null);
    } else {
        final NoSqlObject<W> contextMapEntity = this.connection.createObject();
        contextMap.forEach(new BiConsumer<String, String>() {
            @Override
            public void accept(final String key, final String val) {
                contextMapEntity.set(key, val);
            }
        });
        entity.set("contextMap", contextMapEntity);
    }

    final ThreadContext.ContextStack contextStack = event.getContextStack();
    if (contextStack == null) {
        entity.set("contextStack", (Object) null);
    } else {
        entity.set("contextStack", contextStack.asList().toArray());
    }
}
 
Example 18
Source File: Log4j2QiniuAppender.java    From qiniu-logging-plugin with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void append(LogEvent logEvent) {
    Point point = new Point();
    point.append("timestamp", logEvent.getTimeMillis());
    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().getFormattedMessage());
    point.append("thread_name", logEvent.getThreadName());
    point.append("thread_id", logEvent.getThreadId());
    point.append("thread_priority", logEvent.getThreadPriority());
    if (logEvent.getThrown() != null) {
        Throwable t = logEvent.getThrown().getCause();
        if (t != null) {
            StringBuilder exceptionBuilder = new StringBuilder();
            exceptionBuilder.append(t.getMessage()).append("\n");
            for (StackTraceElement element : logEvent.getThrown().getStackTrace()) {
                exceptionBuilder.append(element.toString()).append("\n");
            }
            point.append("exception", exceptionBuilder.toString());
        } else {
            point.append("exception", logEvent.getThrown().getMessage());
        }
    } 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();
}