|
| 1 | +package com.google.api.logging; |
| 2 | + |
| 3 | +import ch.qos.logback.classic.spi.ILoggingEvent; |
| 4 | +import com.fasterxml.jackson.core.JsonGenerator; |
| 5 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 6 | +import com.fasterxml.jackson.databind.JsonNode; |
| 7 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 8 | +import java.io.IOException; |
| 9 | +import java.util.Map; |
| 10 | +import net.logstash.logback.composite.loggingevent.MdcJsonProvider; |
| 11 | + |
| 12 | +public class SDKLoggingMdcJsonProvider extends MdcJsonProvider { |
| 13 | + |
| 14 | + private final ObjectMapper objectMapper = new ObjectMapper(); |
| 15 | + |
| 16 | + @Override |
| 17 | + public void writeTo(JsonGenerator generator, ILoggingEvent event) throws IOException { |
| 18 | + Map<String, String> mdcProperties = event.getMDCPropertyMap(); |
| 19 | + if (mdcProperties == null || mdcProperties.isEmpty()) { |
| 20 | + return; |
| 21 | + } |
| 22 | + |
| 23 | + boolean hasWrittenStart = false; |
| 24 | + for (Map.Entry<String, String> entry : mdcProperties.entrySet()) { |
| 25 | + String fieldName = entry.getKey(); |
| 26 | + |
| 27 | + if (!hasWrittenStart && getFieldName() != null) { |
| 28 | + generator.writeObjectFieldStart(getFieldName()); |
| 29 | + hasWrittenStart = true; |
| 30 | + } |
| 31 | + generator.writeFieldName(fieldName); |
| 32 | + String entryValueString = entry.getValue(); |
| 33 | + try { |
| 34 | + JsonNode jsonNode = convertToTreeNode(entryValueString); |
| 35 | + if (jsonNode != null) { |
| 36 | + generator.writeTree(jsonNode); |
| 37 | + } else { |
| 38 | + generator.writeObject(entryValueString); |
| 39 | + } |
| 40 | + } catch (JsonProcessingException e) { |
| 41 | + // in case of conversion exception, just use String |
| 42 | + generator.writeObject(entryValueString); |
| 43 | + } |
| 44 | + } |
| 45 | + if (hasWrittenStart) { |
| 46 | + generator.writeEndObject(); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + private JsonNode convertToTreeNode(String jsonString) throws JsonProcessingException { |
| 51 | + return objectMapper.readTree(jsonString); |
| 52 | + } |
| 53 | +} |
0 commit comments