Home > Software engineering >  Replace logging of org.zalando.logbook.Logbook when web request
Replace logging of org.zalando.logbook.Logbook when web request

Time:05-17

I have a Spring Rest Controller which can get this request:

logger_name: org.zalando.logbook.Logbook
message: {"origin":"remote","type":"request","correlation":"91ca9efbe5ed9f5d","protocol":"HTTP/1.1","remote":"172.30.10.1","method":"POST","body":{"bundleCode":"pro","clientInfo":{"clientId":"5-B4QTU240","phoneNumber":" 12223334455"},"interfaceInfo":{"appVersion":"string","appName":"string","platform":"invest"},"planId":1}}

I want to replace my 12223334455 number to 1******4455 in the log, and I've already made a method for it:

private static final String PHONE_MASK_PATTERN = "(?<=^.{2,%d}).";
public static String getPhoneRegexp(int phoneLength) {
        return String.format(PHONE_MASK_PATTERN, phoneLength - 5);
    }

But this request is looged not in handle, it's somewhere inside controller. What is the best way to mask my number using the method?

CodePudding user response:

Just define a BodyFilter bean with your replacement logic, something like this:

@Bean
public BodyFilter bodyFilter() {
    return merge(
            defaultValue(),
            replacePrimitiveJsonProperty(jsonProp -> jsonProp.equals("phoneNumber"), (jsonPropName, jsonPropValue) -> {
                String maskedValue = ... // mask jsonPropValue as you like
                return maskedValue;
            }));
}

Be sure to include the org.zalando:logbook-spring-boot-starter dependency in your project and have the logbook.filter.enabled property set to true

Reference:

https://github.com/zalando/logbook#spring-boot-starter

  • Related