简体   繁体   中英

Save request and response with session id for each request in a text file, REST API Spring Boot

Need help in saving request and response of a REST API in below way,

Session ID:
Request:
{
   {
   request header
   }
   {
   request body
   }
}
Response:
{
    {
     response header
   }
   {
   response body
   }
}

This shouldn't depend on the logging level or any other logging related concepts. Checked many similar questions but no answers for them, Can any one help me in this please, thank you.

Spring Boot - How to log all requests and responses with exceptions in single place?

You could use the HandlerInterceptorAdapter, and write the informations you need on your file :

Spring provides a mechanism for configuring user-defined interceptors to perform actions before and after web requests.

Among the Spring request interceptors, one of the noteworthy interfaces is HandlerInterceptor, which can be used to log the incoming request by implementing the following methods:

preHandle() – this method is executed before the actual controller service method afterCompletion() – this method is executed after the controller is ready to send the response Furthermore, Spring provides the default implementation of HandlerInterceptor interface in the form of HandlerInterceptorAdaptor class which can be extended by the user.

Let's create our own interceptor – by extending HandlerInterceptorAdaptor as:

 @Component public class TaxiFareRequestInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler) { return true; } @Override public void afterCompletion( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { // } } 

http://www.baeldung.com/spring-http-logging

http://www.baeldung.com/spring-mvc-handlerinterceptor

I found answer from Gist https://gist.github.com/int128/e47217bebdb4c402b2ffa7cc199307ba Logging both request and response. Made some minor changes based on my requirement to write into a file instead of logging using java 7 feature.

Path path = Paths.get("home/midoriya/sample.txt");
String strValue = "Whatever the values want to write in file";
Path path = Paths.get(fileName);
byte[] bytes = strValue.getBytes();
Files.write(path, bytes);

or

FileWriter fw = null;
BufferedWriter writer = null;
//  File logFile = null;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    try {
        LocalDate localDate = LocalDate.now();
        File logFile = new File("/home/ramesh/logReqRes"+localDate.getDayOfMonth()+localDate.getMonth()+".txt");
        boolean flag = logFile.createNewFile();
        System.out.println("flag :" + flag);
        if( flag || logFile.length() >= (1024*1024*1024)) 
            fw = new FileWriter(logFile, false);
        else
            fw = new FileWriter(logFile, true);

        writer = new BufferedWriter(fw);
        if (isAsyncDispatch(request)) {
            filterChain.doFilter(request, response);
        } else {
            doFilterWrapped(wrapRequest(request), wrapResponse(response), filterChain);
        }
    } catch (IOException io) {
        io.printStackTrace();
    }
    catch (Exception ex) {
        ex.printStackTrace();

    }
    finally {

        try {

            if (writer != null)
                writer.close();

            if (fw != null)
                fw.close();

        } catch (IOException ex) {

            ex.printStackTrace();

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM