Skip to content

Commit

Permalink
Add additional-field-mapper extension point as described in osiegmar#55
Browse files Browse the repository at this point in the history
  • Loading branch information
Neeme Praks committed Nov 25, 2020
1 parent 655017e commit e3f0b15
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package de.siegmar.logbackgelf;

import ch.qos.logback.classic.spi.ILoggingEvent;

public interface GelfAdditionalFieldMapper {

KeyValue<String, Object> mapAdditionalField(ILoggingEvent event);

class KeyValue<K, V> {
final K key;
final V value;

public KeyValue(K key, V value) {
this.key = key;
this.value = value;
}

@Override
public String toString() {
return key + "=" + value;
}
}

}
15 changes: 15 additions & 0 deletions src/main/java/de/siegmar/logbackgelf/GelfEncoder.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@
import java.math.BigDecimal;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
Expand Down Expand Up @@ -126,6 +128,8 @@ public class GelfEncoder extends EncoderBase<ILoggingEvent> {
*/
private Map<String, Object> staticFields = new HashMap<>();

private List<GelfAdditionalFieldMapper> additionalFieldMappers = new ArrayList<>();

public String getOriginHost() {
return originHost;
}
Expand Down Expand Up @@ -283,6 +287,10 @@ private Object processValue(final String value) {
return value;
}

public void addAdditionalFieldMapper(GelfAdditionalFieldMapper additionalFieldMapper) {
additionalFieldMappers.add(additionalFieldMapper);
}

@Override
public void start() {
if (originHost == null || originHost.trim().isEmpty()) {
Expand Down Expand Up @@ -321,6 +329,13 @@ public byte[] encode(final ILoggingEvent event) {
final String shortMessage = shortPatternLayout.doLayout(event);
final String fullMessage = fullPatternLayout.doLayout(event);
final Map<String, Object> additionalFields = mapAdditionalFields(event);
for (GelfAdditionalFieldMapper additionalFieldMapper : additionalFieldMappers) {
final GelfAdditionalFieldMapper.KeyValue<String, Object> keyValue =
additionalFieldMapper.mapAdditionalField(event);
if (keyValue != null) {
additionalFields.put(keyValue.key, keyValue.value);
}
}

final GelfMessage gelfMessage = new GelfMessage(originHost, shortMessage, fullMessage,
event.getTimeStamp(), LevelToSyslogSeverity.convert(event), additionalFields);
Expand Down

0 comments on commit e3f0b15

Please sign in to comment.