0

I'm using Servlet based web application and want to have proper logging support. I'm using Log4j and when I do receive any requests I want to log it with it's whole properties (not everything, just headers and parameters).

For example:

@WebServlet(name = "Login", value = "/Login")
public class Login extends HttpServlet {
    final static Logger logger = Logger.getLogger(Login.class);

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        logger.info(req); // I want to log request with its 
        // properties: such as request parameters, headers and so on
        // TODO some logic here
    }
}

So, how can I mange to override somehow HttpServletRequests toString() method which actually is an interface. Is it good idea to create Wrapper class for it and can override toString() method there?

Mikheil Zhghenti
  • 734
  • 8
  • 28
  • 2
    Well, to override HttpServletRequest's toString() method, you need to extend/implement it. Why do you even want to? – Chris Neve Mar 29 '19 at 09:38
  • you probably want an interceptor and some library where this is already done – Eugene Mar 29 '19 at 09:38
  • @ChrisNeve I need to log requests parameters into my logging file to see details of each one. – Mikheil Zhghenti Mar 29 '19 at 09:40
  • @Eugene Could you please give me an example? Actually, I'm not using Spring for this project. – Mikheil Zhghenti Mar 29 '19 at 09:41
  • @ChrisNeve Could you please tell me what would be the best practice for my problem? – Mikheil Zhghenti Mar 29 '19 at 09:42
  • HttpServletRequest probably does have a toString() method, but it's going to contain far too much information. Just use logger.info(...) on whatever property you're interested in, for example, logger.info(req.getMethod()) – Chris Neve Mar 29 '19 at 09:51
  • @ChrisNeve In this case to use HttpServletRequest's toString() method is not very useful, because it just prints it's pointer and doesn't provide any "meta data". – Mikheil Zhghenti Mar 29 '19 at 09:55
  • You can refer to this post. https://stackoverflow.com/questions/6631257/how-to-log-properly-http-requests-with-spring-mvc – Yi Zhao Mar 29 '19 at 10:10

2 Answers2

1

You can implement a Filter like this and you can get all request headers and paramters and you can logged into your file

@Component
public class HttpFilter implements Filter {
private static final Logger LOGGER = LogManager.getLogger(HttpLogging.class);

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain 
chain)
        throws IOException, ServletException {
    // TODO Auto-generated method stub

    HttpServletRequest httpServletRequest  = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse  = (HttpServletResponse)response;
    LOGGER.info("logger before method aop FROM FILTER CLASS");
    LOGGER.info("content type " + httpServletRequest.getContentType());
    LOGGER.info("Local Name" + httpServletRequest.getLocalName());
      LOGGER.info("content type " + httpServletRequest.getContentType());
         LOGGER.info("request uri " +  httpServletRequest.getRequestURI());
         LOGGER.info("get Method " + httpServletRequest.getMethod());
         LOGGER.info("query string "  +httpServletRequest.getQueryString() );
         LOGGER.info("server name " + httpServletRequest.getServerName());
         LOGGER.info("server port "  + httpServletRequest.getServerPort());
         LOGGER.info("Parameter names  " + httpServletRequest.getParameter("empid"));


    System.out.println(request.getContentType());

    chain.doFilter(httpServletRequest, httpServletResponse);





  }

}
Aakash Khatavkar
  • 111
  • 1
  • 15
1

Here's what I've used in the past. It uses SLF4J but the statements should be nearly identical to Log4J.

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RequestLogger {

    public static void logRequestAttributes(Logger logger, HttpServletRequest request) {
        logger.debug("Attributes:");
        for (Enumeration<?> attributeNames = request.getAttributeNames(); attributeNames.hasMoreElements(); ) {
            String nextAttributeName = (String) attributeNames.nextElement();

            logger.debug("attribute \"" + nextAttributeName + "\" value is \"" + request.getAttribute(nextAttributeName) + "\"");
        }

        logger.debug("Parameters:");
        for (Enumeration<?> parameterNames = request.getParameterNames(); parameterNames.hasMoreElements(); ) {
            String nextParameterName = (String) parameterNames.nextElement();

            logger.debug("parameter \"" + nextParameterName + "\" value is \"" + request.getParameter(nextParameterName) + "\"");
        }

        logger.debug("Headers:");
        for (Enumeration<?> e = request.getHeaderNames(); e.hasMoreElements(); ) {
            String nextHeaderName = (String) e.nextElement();

            logger.debug("header name: \"" + nextHeaderName + "\" value is \"" + request.getHeader(nextHeaderName) + "\"");
        }

        String logStatement = "Server Name: " + request.getServerName() + "\n";
        logStatement += "\tServer Port: " + request.getServerPort() + "\n";
        logStatement += "\tServlet Path: " + request.getServletPath() + "\n";
        logStatement += "\tMethod: " + request.getMethod() + "\n";
        logStatement += "\tPath info: " + request.getPathInfo() + "\n";
        logStatement += "\tPath translated: " + request.getPathTranslated() + "\n";
        logStatement += "\tRequest URI: " + request.getRequestURI() + "\n";
        logStatement += "\tRequest URL: " + request.getRequestURL() + "\n";
        logStatement += "\tQuery String: " + request.getQueryString() + "\n";
        logStatement += "\tContext path: " + request.getContextPath() + "\n";

        logger.debug(logStatement);
    }
}
stdunbar
  • 16,263
  • 11
  • 31
  • 53