2011-04-11 181 views
3

我有一个简单的Web服务这样的:爪哇 - 在Web服务中丰富的日志记录

@WebService 
public class MyWebService 
{ 
    @WebMethod 
    public String ProcessQuery(@WebParam(name="query") String q) 
    { 
    // Logging here: User IP, etc. 
    } 

    public static void main(String[] args) throws Exception 
    { 
    String address = "http://127.0.0.1:8023/_WebServiceDemo"; 
    Endpoint.publish(address, new MyWebService()); 
    new DocumentServer(); 
    System.out.println("Listening: " + address); 
    } 
} 

我想添加一个测井方法为我服务,以提取信息。我听说过NCSA格式和Log4J,但我不知道如何在服务中使用它们。我想记录用户的IP和其他信息。我该怎么做?

谢谢。

编辑:我应该指出,我的问题的主要部分是如何检索Web方法中的用户的IP,客户端等一些数据。

+0

退房SLF4J的logback和日志记录。两者都非常容易。 – DwB 2011-04-11 19:30:38

回答

3

添加WebServiceContext到类,这样你就可以得到HttpServletRequest

@WebService 
public class MyWebService 
{ 
    @Resource 
    WebServiceContext wsContext; 

    @WebMethod 
    public String ProcessQuery(@WebParam(name="query") String q) 
    { 
     MessageContext messageContext = wsContext.getMessageContext(); 
     HttpServletRequest request = (HttpServletRequest) messageContext.get(SOAPMessageContext.SERVLET_REQUEST); 

     // now you can get anything you want from the request 
    } 

} 
+0

谢谢。我将这些添加到我的服务中(我将** wsContext **更改为**上下文**我假设这就是您的意思),但是当我运行它时**请求**将为空。什么不见​​了?我应该提到我运行Silverlight应用程序的请求。对于日志记录部分,Log4J arlight?我想我会去用它。 – 2011-04-11 19:40:27

+0

是的,抱歉它是错字...我猜这个请求是空的,因为你使用Endpoint.publish发布它,而不是使用servlet容器。基本上这不是一个很好的方式,因为它不会提供一个非常好的Http服务器。你打算继续这种方式还是转移到真正的服务器,如Tomcat/Jetty/Jboss? – Tarlog 2011-04-11 19:50:31

+0

无论如何,如果您不打算移动到servlet容器,请尝试调查消息上下文,它具有哪些属性? – Tarlog 2011-04-11 19:53:53