CXF报文日志记录

来源:互联网 发布:淘宝图片轮播怎么制作 编辑:程序博客网 时间:2024/06/10 13:35

由于项目需要记录系统间的报文,上网搜集资料,最终解决问题。记录如下:


在项目中是将报文(出参,入参)记录到log文件中,一个webservice文件夹,日志以日期命名

1.首先定义拦截器。

出参拦截器

public class RecordOutInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

    public RecordOutInterceptor() {
        super(Phase.PRE_STREAM);
    }

    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        try {

            OutputStream os = message.getContent(OutputStream.class);

            CachedOutputStream cs = new CachedOutputStream();

            message.setContent(OutputStream.class, cs);
            message.getInterceptorChain().doIntercept(message);
            CachedOutputStream csnew = (CachedOutputStream) message.getContent(OutputStream.class);
            InputStream in = csnew.getInputStream();
            String xml = IOUtils.toString(in);
            // 将报文信息写入日志文件
            WebServiceUtil.log(xml);
            // 这里对xml做处理,处理完后同理,写回流中
            IOUtils.copy(new ByteArrayInputStream(xml.getBytes()), os);
            cs.close();
            os.flush();

            message.setContent(OutputStream.class, os);

        } catch (Exception e) {
            e.printStackTrace();
            // log.error("Error when split original inputStream. CausedBy : " +
            // "\n" + e);
        }
    }

    private class CachedStream extends CachedOutputStream {

        public CachedStream() {

            super();

        }

        protected void doFlush() throws IOException {

            currentStream.flush();

        }

        protected void doClose() throws IOException {

        }

        protected void onWrite() throws IOException {

        }

    }
}

2.入参拦截器,

public class RecordInInterceptor extends AbstractLoggingInterceptor {
    private static final Logger LOG = LogUtils.getLogger(RecordInInterceptor.class);

    public RecordInInterceptor() {
        super("receive");
    }

    public RecordInInterceptor(String phase) {
        super(phase);
    }

    public RecordInInterceptor(String id, String phase) {
        super(id, phase);
    }

    public RecordInInterceptor(int lim) {
        this();
        this.limit = lim;
    }

    public RecordInInterceptor(String id, int lim) {
        this(id, "receive");
        this.limit = lim;
    }

    public RecordInInterceptor(PrintWriter w) {
        this();
        this.writer = w;
    }

    public RecordInInterceptor(String id, PrintWriter w) {
        this(id, "receive");
        this.writer = w;
    }

    public void handleMessage(Message message) throws Fault {
        Logger logger = getMessageLogger(message);
        if ((this.writer != null) || (logger.isLoggable(Level.INFO))) {
            logging(logger, message);
        }
    }

    Logger getMessageLogger(Message message) {
        Endpoint ep = message.getExchange().getEndpoint();
        if ((ep == null) || (ep.getEndpointInfo() == null)) {
            return getLogger();
        }
        EndpointInfo endpoint = ep.getEndpointInfo();
        if (endpoint.getService() == null) {
            return getLogger();
        }
        Logger logger = (Logger) endpoint.getProperty("MessageLogger", Logger.class);
        if (logger == null) {
            String serviceName = endpoint.getService().getName().getLocalPart();
            InterfaceInfo iface = endpoint.getService().getInterface();
            String portName = endpoint.getName().getLocalPart();
            String portTypeName = iface.getName().getLocalPart();
            String logName = "org.apache.cxf.services." + serviceName + "." + portName + "." + portTypeName;

            logger = LogUtils.getL7dLogger(getClass(), null, logName);
            endpoint.setProperty("MessageLogger", logger);
        }
        return logger;
    }

    protected void logging(Logger logger, Message message) throws Fault {
        if (message.containsKey(LoggingMessage.ID_KEY)) {
            return;
        }
        String id = (String) message.getExchange().get(LoggingMessage.ID_KEY);
        if (id == null) {
            id = LoggingMessage.nextId();
            message.getExchange().put(LoggingMessage.ID_KEY, id);
        }
        message.put(LoggingMessage.ID_KEY, id);
        LoggingMessage buffer = new LoggingMessage("Inbound Message\n----------------------------", id);
        if (!Boolean.TRUE.equals(message.get("decoupled.channel.message"))) {
            Integer responseCode = (Integer) message.get(Message.RESPONSE_CODE);
            if (responseCode != null) {
                buffer.getResponseCode().append(responseCode);
            }
        }
        String encoding = (String) message.get(Message.ENCODING);
        if (encoding != null) {
            buffer.getEncoding().append(encoding);
        }
        String httpMethod = (String) message.get("org.apache.cxf.request.method");
        if (httpMethod != null) {
            buffer.getHttpMethod().append(httpMethod);
        }
        String ct = (String) message.get("Content-Type");
        if (ct != null) {
            buffer.getContentType().append(ct);
        }
        Object headers = message.get(Message.PROTOCOL_HEADERS);
        if (headers != null) {
            buffer.getHeader().append(headers);
        }
        String uri = (String) message.get("org.apache.cxf.request.url");
        if (uri == null) {
            String address = (String) message.get(Message.ENDPOINT_ADDRESS);
            uri = (String) message.get("org.apache.cxf.request.uri");
            if ((uri != null) && (uri.startsWith("/"))) {
                if ((address != null) && (!address.startsWith(uri))) {
                    if ((address.endsWith("/")) && (address.length() > 1)) {
                        address = address.substring(0, address.length());
                    }
                    uri = address + uri;
                }
            } else {
                uri = address;
            }
        }
        if (uri != null) {
            buffer.getAddress().append(uri);
            String query = (String) message.get(Message.QUERY_STRING);
            if (query != null) {
                buffer.getAddress().append("?").append(query);
            }
        }
        if ((!isShowBinaryContent()) && (isBinaryContent(ct))) {
            buffer.getMessage().append("--- Binary Content ---").append('\n');
            log(logger, buffer.toString());
            return;
        }
        InputStream is = (InputStream) message.getContent(InputStream.class);
        if (is != null) {
            logInputStream(message, is, buffer, encoding, ct);
        } else {
            Reader reader = (Reader) message.getContent(Reader.class);
            if (reader != null) {
                logReader(message, reader, buffer);
            }
        }
        log(logger, formatLoggingMessage(buffer));
        // 将报文信息写入日志文件
        try {
            WebServiceUtil.log(buffer.getPayload().toString());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    protected void logReader(Message message, Reader reader, LoggingMessage buffer) {
        try {
            CachedWriter writer = new CachedWriter();
            IOUtils.copyAndCloseInput(reader, writer);
            message.setContent(Reader.class, writer.getReader());
            if (writer.getTempFile() != null) {
                buffer.getMessage().append("\nMessage (saved to tmp file):\n");
                buffer.getMessage().append("Filename: " + writer.getTempFile().getAbsolutePath() + "\n");
            }
            if ((writer.size() > this.limit) && (this.limit != -1)) {
                buffer.getMessage().append("(message truncated to " + this.limit + " bytes)\n");
            }
            writer.writeCacheTo(buffer.getPayload(), this.limit);
        } catch (Exception e) {
            throw new Fault(e);
        }
    }

    protected void logInputStream(Message message, InputStream is, LoggingMessage buffer, String encoding, String ct) {
        CachedOutputStream bos = new CachedOutputStream();
        if (this.threshold > 0L) {
            bos.setThreshold(this.threshold);
        }
        try {
            InputStream bis = (is instanceof DelegatingInputStream) ? ((DelegatingInputStream) is).getInputStream() : is;

            IOUtils.copyAtLeast(bis, bos, this.limit == -1 ? 2147483647 : this.limit);
            bos.flush();
            bis = new SequenceInputStream(bos.getInputStream(), bis);
            if ((is instanceof DelegatingInputStream)) {
                ((DelegatingInputStream) is).setInputStream(bis);
            } else {
                message.setContent(InputStream.class, bis);
            }
            if (bos.getTempFile() != null) {
                buffer.getMessage().append("\nMessage (saved to tmp file):\n");
                buffer.getMessage().append("Filename: " + bos.getTempFile().getAbsolutePath() + "\n");
            }
            if ((bos.size() > this.limit) && (this.limit != -1)) {
                buffer.getMessage().append("(message truncated to " + this.limit + " bytes)\n");
            }
            writePayload(buffer.getPayload(), bos, encoding, ct);

            bos.close();
        } catch (Exception e) {
            throw new Fault(e);
        }
    }

    protected String formatLoggingMessage(LoggingMessage loggingMessage) {
        return loggingMessage.toString();
    }

    protected Logger getLogger() {
        return LOG;
    }
}

3.配置XML文件:

    <jaxws:endpoint id="loanService"
        implementor="#testServiceImpl" address="/loanService">
        <jaxws:inInterceptors>
            <!-- <bean class="org.apache.cxf.interceptor.LoggingInInterceptor" /> -->
            <bean class="ms.platform.bpm.util.RecordInInterceptor"></bean>
        </jaxws:inInterceptors>
        <jaxws:outInterceptors>
            <bean class="ms.platform.bpm.util.RecordOutInterceptor"></bean>
        </jaxws:outInterceptors>
        <jaxws:properties>
            <entry key="schema-validation-enabled" value="false" />
        </jaxws:properties>
    </jaxws:endpoint>

0 0
原创粉丝点击