We have a few servlets like the one below, taking JSON request and produce JSON response. And the requirement is to log all API call traffic.
import org.slf4j.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CommentServlet {
private static final Logger LOG = LoggerFactory.getLogger(CommentServlet.class);
public void postComment(HttpServletRequest request, HttpServletResponse response) throws IOException {
String commentRequested = request.getParameter("comment");
LOG.info(commentRequested);
Object postResultModel = processComment(commentRequested);
JsonUtil.writeResponse(response, postResultModel);
}
/**
* doesn't reallty matter what processComment does
*/
public Object processComment(String comment) {
return new Object();
}
}
import org.slf4j.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class JsonUtil {
private static final Logger LOG = LoggerFactory.getLogger(JsonUtil.class);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public static void writeResponse(HttpServletResponse response, Object modelObject) throws IOException {
String modelJson = OBJECT_MAPPER.writeValueAsString(modelObject);
LOG.info(modelJson);
response.setContentType("application/json");
response.getWriter().write(modelJson);
}
}
if you can mainly review how the logging is done, I'd like feedback on the general approach as much as whether there's any way to improve it.