如何在 Spring Boot 应用程序中编辑 RestTemplate 日志中的用户名、密码信息
19:16:30.017 [http-nio-9550-exec-7] DEBUG o.s.web.client.RestTemplate - Writing [{grant_type=[password], client_id=[eve-client], client_secret=[v8nhI8YzyOLmP3tPyFwrMsP1rSCHOZBE], scope=[offline_access], username=[john], password=[FooBar..][]}] as "application/x-www-form-urlencoded"
除非您想基于某些正则表达式实现自定义日志编写器,否则我建议使用
https://github.com/zalando/logbook?tab=readme-ov-file#spring-boot-starter
。
它与 RestTemplate 很好地集成。 从那里您可以配置自己的 BodyFilter
class CustomUrlEncodedBodyFilter implements BodyFilter {
private final Set<String> namesToObfuscate;
private static final Predicate<String> FORM_URL_ENCODED =
MediaTypeQuery.compile("x-www-form-urlencoded");
public CustomUrlEncodedBodyFilter(Set<String> namesToObfuscate) {
this.namesToObfuscate = namesToObfuscate;
}
@Override
public String filter(@Nullable final String contentType, final String body) {
return FORM_URL_ENCODED.test(contentType) ? obfuscate(body) : body;
}
private String obfuscate(final String body) {
// Do the obfuscate here, ie parse body (should probably works with java.net.URL?) and replace values of items listed in namesToObfuscate
return body;
}
}
@Bean
public BodyFilter bodyFilter() {
return merge(
defaultValue(),
new CustomUrlEncodedBodyFilter(Set.of("username","password"))); //You can extract those properties in external file
}