如何在Apache Camel CXF中配置Log4J输出日志到文件?
CXF SOAP消息日志输出到Log4j文件解决方案
问题根源
CXF默认使用JUL(java.util.logging)作为日志实现,默认仅输出到控制台,之前的配置未生效通常是依赖缺失、配置内容错误或者打包后配置文件位置不对导致。
操作步骤
1. 引入必要依赖
首先添加JUL到SLF4J的桥接器,将CXF默认的JUL日志转发到SLF4J,再由SLF4J绑定到你的Log4j实现,Maven依赖示例如下:
<dependency> <groupId>org.slf4j</groupId> <artifactId>jul-to-slf4j</artifactId> <version>1.7.36</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-features-logging</artifactId> <version>匹配你的CXF版本</version> </dependency>
如果使用Log4j2,还需确保已引入log4j-slf4j-impl绑定依赖。
2. 修正CXF日志实现绑定配置
你之前创建的META-INF/cxf/org.apache.cxf.logger文件内容需要填写正确的日志实现类,文件内容如下:
org.apache.cxf.common.logging.Slf4jLogger
同时确认该文件放在src/main/resources目录下,打包后会自动放到类路径根目录,不会被漏掉。
3. 自定义CXF日志Feature(推荐)
URI参数中的loggingFeatureEnabled=true使用的是CXF默认的日志实例,自定义日志Feature可以指定日志名称,方便Log4j规则匹配,代码示例如下:
// 初始化自定义日志Feature LoggingFeature loggingFeature = new LoggingFeature(); loggingFeature.setLoggingSizeLimit(-1); loggingFeature.setPrettyLogging(true); loggingFeature.setLogLevel(Level.INFO); loggingFeature.setLoggerName("cxf.soap.message"); // 配置CXF端点 CxfEndpoint cxfEndpoint = new CxfEndpoint(); cxfEndpoint.setAddress(WebserviceHost + "SOAP/v2/Webservice"); cxfEndpoint.setServiceClass(de.Webservice.class); cxfEndpoint.setDataFormat(DataFormat.POJO); cxfEndpoint.setSynchronous(true); cxfEndpoint.getFeatures().add(loggingFeature); // 路由中使用自定义端点 from(cxfEndpoint) // 后续路由逻辑
如果不想修改路由代码,也可以保留原有URI配置,后续直接配置org.apache.cxf.services包的日志输出规则即可。
4. 配置Log4j日志输出规则
在你的Log4j配置文件中添加对应日志的输出规则,Log4j2 XML配置示例如下:
<Configuration> <Appenders> <!-- 新增CXF SOAP消息专用输出文件 --> <RollingFile name="CxfSoapLog" fileName="./logs/cxf-soap.log" filePattern="./logs/cxf-soap-%d{yyyy-MM-dd}.log.gz"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger - %msg%n"/> <Policies> <TimeBasedTriggeringPolicy interval="1"/> <SizeBasedTriggeringPolicy size="100MB"/> </Policies> <DefaultRolloverStrategy max="30"/> </RollingFile> </Appenders> <Loggers> <!-- 匹配自定义的CXF日志名称,输出到指定文件 --> <Logger name="cxf.soap.message" level="INFO" additivity="false"> <AppenderRef ref="CxfSoapLog"/> </Logger> <!-- 如果没有自定义Feature,使用下面的规则匹配默认CXF日志 --> <!-- <Logger name="org.apache.cxf.services" level="INFO" additivity="false"> <AppenderRef ref="CxfSoapLog"/> </Logger> --> </Loggers> </Configuration>
失效排查
- 检查项目依赖中是否存在冲突的日志实现,比如同时引入了logback和log4j,会导致日志绑定混乱
- Spring Boot项目可直接在
application.yml中添加logging.level.org.apache.cxf: INFO快速验证日志是否正常输出 - 确认JUL桥接已开启,Spring Boot会自动初始化
jul-to-slf4j,普通项目需要在启动类中添加SLF4JBridgeHandler.install();完成桥接初始化
内容的提问来源于stack exchange,提问作者Burner
相关产品推荐
相关产品推荐

