Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Rich logging in web services

I have a simple web service like this:

@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);
    }
}

I want to add a logging method for my service to extract information. I've heard about NCSA format and Log4J but I don't know how to use them in the service. I want to log user's ip and other info. How can I do it?

Thanks.

Edit: I should note that the main part of my question is how can I retrieve some data such as user's IP, client, etc. in the web method.

like image 645
Alireza Noori Avatar asked Nov 29 '25 01:11

Alireza Noori


1 Answers

Add WebServiceContext to your class, so you can get the 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
    }

}
like image 165
Tarlog Avatar answered Nov 30 '25 15:11

Tarlog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!