2

Context: We are using com.fasterxml.jackson.databind.ObjectMapper's readValue() method to convert JSON to Java POJO. When the JsonParseException or JsonMappingException occurs, the original data excerpts (JSON content) is being printed in the logs.

Issue: Our JSON may contain sensitive-data, so it shouldn't get logged to meet the security compliance.

The options we are considering...

Option-1: wrap the readValue() method with JsonParseException, JsonMappingException and add clearLocation()

fyi... clearLocation() on JsonParseException and JsonMappingException removes context information from exception's message

        try {
            objectMapper.readValue(jsonContent, pojoObject);
        } catch (JsonParseException | JsonMappingException e) {
            e.clearLocation();
            throw e;
        } 

The downside of this solution is, readValue() method is used in lot of places across multiple applications. So we need to deal with lot of code changes. And we shouldn't forget to call clearLocation() in the future implementations.

Option-2: Create custom ObjectMapper

public class CustomObjectMapper {
    private static ObjectMapper objectMapper = new ObjectMapper();
    
    // showing only one method to simplify
    public static <T> T convertJsonToPojo(String content, Class<T> valueType)
            throws IOException, JsonParseException, JsonMappingException {
        try {
            return objectMapper.readValue(content, valueType);
        } catch (JsonParseException | JsonMappingException e) {
            e.clearLocation();
            throw e;
        } catch (JsonProcessingException e) {
            e.clearLocation();
            throw e;
        } catch (Exception e) {
            throw e;
        }
    }
}

Please let me know if you came across the similar situation and handled it differently.

Ray
  • 21
  • 2
  • shouldn't log only the fields that you want to see? otherwise even with tools like elk or splunk, searching through the logs are going to be very hectic – tsamridh86 Aug 17 '21 at 05:07
  • 1
    The second option is OK but I would consider using aspects or exception handlers. – Marek Żylicz Aug 18 '21 at 08:35

1 Answers1

3

You can use aspects;

@Aspect
@Component
public class OMAspect {

    @Around("within(<your base package>..*)")
    public Object aroundOMMethods(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
           return joinPoint.proceed();
        } catch (JsonProcessingException e) {
            e.clearLocation();
            throw e;
        } catch (Throwable e) {
            throw e;
        }
    }
}
Kemal Kaplan
  • 932
  • 8
  • 21