Web 请求时替换 org.zalando.logbook.Logbook 的日志记录

Replace logging of org.zalando.logbook.Logbook when web request

我有一个 Spring Rest Controller 可以得到这个请求:

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}}

我想把日志里的+12223334455号码替换成+1******4455,我已经做了方法:

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

但是这个请求不是在句柄中,而是在控制器内部的某个地方。使用此方法屏蔽我的号码的最佳方法是什么?

只需用您的替换逻辑定义一个 BodyFilter bean,如下所示:

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

确保在项目中包含 org.zalando:logbook-spring-boot-starter 依赖项并将 logbook.filter.enabled 属性 设置为 true

参考:

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