Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Map Logback log levels to allowed GCP Stackdriver severities #1141

Merged
merged 1 commit into from
Jun 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package io.micronaut.gcp.logging;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.contrib.json.JsonFormatter;
Expand All @@ -35,11 +36,21 @@
* @since 3.2.0
*/
public class StackdriverJsonLayout extends JsonLayout {
// GPC Logging has limited Severity values: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity
private static final Map<Level, String> LOGBACK_TO_GCP_SEVERITY_MAP = Map.of(
Level.ALL, "DEBUG",
Level.TRACE, "DEBUG",
Level.DEBUG, "DEBUG",
Level.INFO, "INFO",
Level.WARN, "WARNING",
Level.ERROR, "ERROR"
);
private static final String DEFAULT_LOG_SEVERITY = "DEBUG";

private static final Set<String> FILTERED_MDC_FIELDS = new HashSet<>(Arrays.asList(
StackdriverTraceConstants.MDC_FIELD_TRACE_ID,
StackdriverTraceConstants.MDC_FIELD_SPAN_ID,
StackdriverTraceConstants.MDC_FIELD_SPAN_EXPORT));
StackdriverTraceConstants.MDC_FIELD_TRACE_ID,
StackdriverTraceConstants.MDC_FIELD_SPAN_ID,
StackdriverTraceConstants.MDC_FIELD_SPAN_EXPORT));

// Inline in the constructor, JsonMapper.createDefault() cannot find an implementation via the ServiceLoader, so do it lazily.
private static final Supplier<JsonFormatter> JSON_FORMATTER_SUPPLIER = SupplierUtil
Expand Down Expand Up @@ -96,13 +107,13 @@ protected Map<String, Object> toJsonMap(ILoggingEvent event) {
}
if (this.includeTimestamp) {
map.put(StackdriverTraceConstants.TIMESTAMP_SECONDS_ATTRIBUTE,
TimeUnit.MILLISECONDS.toSeconds(event.getTimeStamp()));
TimeUnit.MILLISECONDS.toSeconds(event.getTimeStamp()));
map.put(StackdriverTraceConstants.TIMESTAMP_NANOS_ATTRIBUTE,
TimeUnit.MILLISECONDS.toNanos(event.getTimeStamp() % 1_000));
TimeUnit.MILLISECONDS.toNanos(event.getTimeStamp() % 1_000));
}

add(StackdriverTraceConstants.SEVERITY_ATTRIBUTE, this.includeLevel,
String.valueOf(event.getLevel()), map);
LOGBACK_TO_GCP_SEVERITY_MAP.getOrDefault(event.getLevel(), DEFAULT_LOG_SEVERITY), map);
add(JsonLayout.THREAD_ATTR_NAME, this.includeThreadName, event.getThreadName(), map);
add(JsonLayout.LOGGER_ATTR_NAME, this.includeLoggerName, event.getLoggerName(), map);

Expand All @@ -124,7 +135,7 @@ protected Map<String, Object> toJsonMap(ILoggingEvent event) {
addThrowableInfo(JsonLayout.EXCEPTION_ATTR_NAME, this.includeException, event, map);
addTraceId(event, map);
add(StackdriverTraceConstants.SPAN_ID_ATTRIBUTE, this.includeSpanId,
event.getMDCPropertyMap().get(StackdriverTraceConstants.MDC_FIELD_SPAN_ID), map);
event.getMDCPropertyMap().get(StackdriverTraceConstants.MDC_FIELD_SPAN_ID), map);
if (this.customJson != null && !this.customJson.isEmpty()) {
for (Map.Entry<String, Object> entry : this.customJson.entrySet()) {
map.putIfAbsent(entry.getKey(), entry.getValue());
Expand All @@ -140,20 +151,20 @@ protected Map<String, Object> toJsonMap(ILoggingEvent event) {
* @return formated tracedId
*/
protected String formatTraceId(final String traceId) {
return ("00000000000000000000000000000000" + traceId).substring(traceId.length());
return ("00000000000000000000000000000000" + traceId).substring(traceId.length());
}

private void addTraceId(ILoggingEvent event, Map<String, Object> map) {
if (!this.includeTraceId) {
return;
}
String traceId =
event.getMDCPropertyMap().get(StackdriverTraceConstants.MDC_FIELD_TRACE_ID);
event.getMDCPropertyMap().get(StackdriverTraceConstants.MDC_FIELD_TRACE_ID);
if (!StringUtils.isEmpty(traceId)
&& !StringUtils.isEmpty(this.projectId)
&& !this.projectId.endsWith("_IS_UNDEFINED")) {
&& !StringUtils.isEmpty(this.projectId)
&& !this.projectId.endsWith("_IS_UNDEFINED")) {
traceId = StackdriverTraceConstants.composeFullTraceName(
this.projectId, formatTraceId(traceId));
this.projectId, formatTraceId(traceId));
}

add(StackdriverTraceConstants.TRACE_ID_ATTRIBUTE, this.includeTraceId, traceId, map);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package io.micronaut.gcp.logging

import ch.qos.logback.classic.Level
import ch.qos.logback.classic.LoggerContext
import ch.qos.logback.classic.spi.LoggingEvent
import spock.lang.Specification

import java.util.concurrent.TimeUnit

class StackdriverJsonLayoutSpec extends Specification {
StackdriverJsonLayout stackdriverJsonLayout = new StackdriverJsonLayout()
LoggerContext loggerContext = new LoggerContext()

void "should properly map log level to GCP severity"() {
given:
def event = new LoggingEvent(
this.class.canonicalName, loggerContext.getLogger(this.class), logLevel, 'the message', new IllegalArgumentException('exception message'), new Object[]{}
)
event.setMDCPropertyMap([:])

when:
def result = stackdriverJsonLayout.toJsonMap(event)

then:
result['severity'] == expectedSeverity
result['message'] == 'the message\njava.lang.IllegalArgumentException: exception message\n'
result['thread'] == 'main'
result['logger'] == this.class.canonicalName
result['timestampSeconds'] == TimeUnit.MILLISECONDS.toSeconds(event.timeStamp)
result['timestampNanos'] == TimeUnit.MILLISECONDS.toNanos(event.getTimeStamp() % 1_000)

where:
logLevel || expectedSeverity
Level.ALL || 'DEBUG'
Level.TRACE || 'DEBUG'
Level.DEBUG || 'DEBUG'
Level.INFO || 'INFO'
Level.WARN || 'WARNING'
Level.ERROR || 'ERROR'
}
}
Loading