Spring Boot集成CXF RS如何编程式配置美化HTTP请求响应日志
解决方案
基于Spring Boot + CXF的环境,不需要XML配置,核心逻辑是给CXF全局Bus注册开启了美化输出的LoggingFeature,有两种常用实现方式:
方法1:直接注册LoggingFeature Bean(推荐)
Spring Boot CXF 自动配置会自动扫描所有实现了Feature接口的Bean,加载到全局Bus中,直接配置即可:
import org.apache.cxf.ext.logging.LoggingFeature; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class CxfConfig { @Bean public LoggingFeature cxfLoggingFeature() { LoggingFeature loggingFeature = new LoggingFeature(); // 开启请求/响应报文美化格式化 loggingFeature.setPrettyLogging(true); // 可选配置:设置单条日志最大输出长度,默认1MB loggingFeature.setLimit(10 * 1024 * 1024); // 可选配置:是否打印请求/响应头 loggingFeature.setLogHeaders(true); // 可选配置:是否打印请求/响应正文 loggingFeature.setLogPayload(true); return loggingFeature; } }
方法2:手动给Bus挂载LoggingFeature
如果需要更灵活的加载控制(比如按环境条件开启日志),可以直接注入全局Bus手动挂载:
import jakarta.annotation.PostConstruct; import org.apache.cxf.Bus; import org.apache.cxf.ext.logging.LoggingFeature; import org.springframework.stereotype.Component; @Component public class CxfLoggingConfig { private final Bus cxfBus; public CxfLoggingConfig(Bus cxfBus) { this.cxfBus = cxfBus; } @PostConstruct public void enableLogging() { LoggingFeature loggingFeature = new LoggingFeature(); loggingFeature.setPrettyLogging(true); // 其他自定义配置同上 cxfBus.getFeatures().add(loggingFeature); } }
额外配置说明
- 如果你使用的是3.3之前的老版本CXF,
LoggingFeature的包路径为org.apache.cxf.feature.LoggingFeature,配置逻辑完全一致 - 可在
application.properties中调整CXF日志输出级别:
# 调整CXF业务日志级别 logging.level.org.apache.cxf.services=INFO
内容的提问来源于stack exchange,提问作者walter33
相关产品推荐
相关产品推荐

