Last active
February 2, 2023 15:41
-
-
Save ishults/1770625972c9aa2503c1b52300aaed32 to your computer and use it in GitHub Desktop.
The class that will handle filtering the log statements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Plugin(name = 'logmask', category = 'Converter') | |
@ConverterKeys(['cm']) | |
class LogMaskingConverter extends LogEventPatternConverter { | |
private static final String NAME = 'cm' | |
private static final String JSON_REPLACEMENT_REGEX = "\"\$1\": \"****\"" | |
private static final String JSON_KEYS = ['ssn', 'private', 'creditCard'].join('|') | |
private static final Pattern JSON_PATTERN = Pattern.compile(/"(${JSON_KEYS})": "([^"]+)"/) | |
LogMaskingConverter(String[] options) { | |
super(NAME, NAME) | |
} | |
static LogMaskingConverter newInstance(final String[] options) { | |
return new LogMaskingConverter(options) | |
} | |
@Override | |
void format(LogEvent event, StringBuilder outputMessage) { | |
String message = event.message.formattedMessage | |
String maskedMessage = message | |
if (event.marker?.name == LoggingMarkers.JSON.name) { | |
try { | |
maskedMessage = mask(message) | |
} catch (Exception e) { | |
maskedMessage = message // Although if this fails, it may be better to not log the message | |
} | |
} | |
outputMessage.append(maskedMessage) | |
} | |
private String mask(String message) { | |
StringBuffer buffer = new StringBuffer() | |
Matcher matcher = JSON_PATTERN.matcher(message) | |
while (matcher.find()) { | |
matcher.appendReplacement(buffer, JSON_REPLACEMENT_REGEX) | |
} | |
matcher.appendTail(buffer) | |
return buffer.toString() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment