Logging for HTTP servlet requests #61
Replies: 2 comments
-
The Possible class: package org.kiwiproject.logging;
// imports
@UtilityClass
public class KiwiLogging {
// Refs:
// * https://sonarcloud.io/organizations/kiwiproject/rules?open=javasecurity%3AS5145&rule_key=javasecurity%3AS5145
// * https://rules.sonarsource.com/java/RSPEC-5145
private static final Pattern SANITIZER_PATTERN = Pattern.compile("[\n\r\t]");
public static String sanitizeForLogging(CharSequence msg) {
return SANITIZER_PATTERN.matcher(original).replaceAll("_");
}
} Note that the method is named as a verb phrase, e.g. "sanitize the input for logging", not in the past tense (as with sanitized). Of course, just writing the above made me think of a whole lot of possibilities for this class, since you basically want to apply this to the arguments that are injected into a log message template, e.g. LOG.info("The request URL was {}, sanitizeForLogging(requestURL)); Because you also want to then lazily call this in case the log level is not active, e.g. LOG.info("The request URL was {}, lazy(() -> sanitizeForLogging(requestURL))); And if you need to sanitize multiple arguments this starts to get really messy. The better solution would be for the logging libraries to provide this sanitization, perhaps as an option to always replace So, you could add something like: public static Supplier<String> lazySanitizeForLogging(CharSequence msg) {
return lazy(() -> SANITIZER_PATTERN.matcher(original).replaceAll("_"));
} Starting with these two methods might be fine. |
Beta Was this translation helpful? Give feedback.
-
Re-reviewing this, it's kind of funny because one the one hand, the above code sanitizes input by replacing newlines and carriage returns, but on the other it intentionally adds line separators to the log statements! Maybe the idea was that sanitizing user input, e.g., from query parameters, was needed, but in our own logging it is acceptable to add newlines. Regardless, it would probably be best to remove those newlines. |
Beta Was this translation helpful? Give feedback.
-
Here's some half-baked (maybe not even half) experimental code derived from some actual code I found in one of our production services that does some very minimal request logging. Since we really just don't interact with the raw servlet API much at all, I'm not sure it's worth anything more than just as experimental, throwaway code anyway.
But here is is for posterity, in case we ever care about it.
Beta Was this translation helpful? Give feedback.
All reactions