这需要一些样板代码,但它不依赖于应用服务器。
AttachAttributesFilter 将 startTime 和 UUID 添加到属性。然后在 LogSoapHandler 中为入站和出站消息读取这些属性。
日志中的简单搜索将显示特定 UUID 的输入和输出。
@WebFilter("/yourwebservice")
public class AttachAttributesFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setAttribute("STARTTIME", System.currentTimeMillis());
request.setAttribute("UUID",java.util.UUID.randomUUID().toString());
chain.doFilter(request, response);
}
}
然后我使用 LogSoapHander 中的属性
public class LogSoapHandler implements
javax.xml.ws.handler.soap.SOAPHandler<SOAPMessageContext> {
public boolean handleMessage(SOAPMessageContext messagecontext) {
Boolean outbound = (Boolean) messagecontext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
String messageID = (String) httpSR.getAttribute("UUID");
Object startTime = httpSR.getAttribute("STARTTIME");
try {
final SOAPMessage message = messagecontext.getMessage();
String encoding = getMessageEncoding(message);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
boolean fault = (message.getSOAPBody().hasFault());
message.writeTo(baos);
String body = (baos.toString(encoding));
log.info(outbound+"|"+messageID+"|"+startTime+"|"+System.currentTimeMillis()+"|"+body+"|"+fault));
} catch (SOAPException | IOException ex) {
//handle your error
}
return true;
}
private String getMessageEncoding(SOAPMessage msg) throws SOAPException {
String encoding = "utf-8";
if (msg.getProperty(SOAPMessage.CHARACTER_SET_ENCODING) != null) {
encoding = msg.getProperty(SOAPMessage.CHARACTER_SET_ENCODING)
.toString();
}
return encoding;
}
并完成 HandlerChain 锅炉板:
@HandlerChain(file="loghandler.xml")
public class MyWSDL {
..
}
日志处理程序.xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<javaee:handler-chains
xmlns:javaee="http://java.sun.com/xml/ns/javaee"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<javaee:handler-chain>
<javaee:handler>
<javaee:handler-class>xxx.LogSoapHandler</javaee:handler-class>
</javaee:handler>
</javaee:handler-chain>
</javaee:handler-chains>