lundi 13 juin 2016

CXF Interceptor phase for cleaning up MDC

Do you have a recommendation for which Apache CXF phase to hook an outbound interceptor to clean up the SLF4J Mapped Diagnostic Context (MDC)?

I see some code available publicly on GitHub that fires the clearing of the logging context at the Phase.PRE_STREAM. My first thought was to call it at the very last Phase.SETUP_ENDING.

EDIT: After deploying it I realized that I also needed to wire it to outFaultInterceptors. To get that to work I had to change Phase.SETUP_ENDING to Phase.MARSHALL. But I have no idea why or whether that's the best phase.

I'm new to Apache CXF and want to make sure I don't break something using the wrong phase.

Here's my code

import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.slf4j.MDC;

public class MdcCleanUpInterceptor extends AbstractPhaseInterceptor<Message> {

    public MdcCleanUpInterceptor() {
        super(Phase.MARSHAL);
    }

    @Override
    public void handleMessage(Message message) {
        MDC.clear();
    }
}

and my Spring definition

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jaxrs="http://cxf.apache.org/jaxrs"
       xmlns:cxf="http://cxf.apache.org/core"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
            http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
            http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
    <cxf:bus>
        <cxf:outInterceptors>
            <ref bean="mdcCleanUpInterceptor"/>
        </cxf:outInterceptors>
        <cxf:outFaultInterceptors>
            <ref bean="mdcCleanUpInterceptor"/>
        </cxf:outFaultInterceptors>
    </cxf:bus>

    <bean id="mdcCleanUpInterceptor" class="MdcCleanUpInterceptor"/>
</beans>

Aucun commentaire:

Enregistrer un commentaire