Spring boot's correct posture for logging

Previous articles

Spring Boot log processing are you still using Logback?

Brief introduction

The previous article focuses on the configuration of Log4j2, and this article focuses on the application of unified log processing. The following includes HTTP request log processing and Exception exception log processing.

HTTP request log

img

1. Clear the contents of log records

Example: user, IP address, Method, URI, request parameter, request body

2. Global interception of MDCFilter.java

package com.anoyi.config.server;

import lombok.extern.log4j.Log4j2;
import org.slf4j.MDC;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Intercept request information, add to log
 */
@Component
@Log4j2
public class MDCFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        try {
            MDC.put("user", request.getRemoteUser());
            String query = request.getQueryString() != null ? "?" + request.getQueryString() : "";
            if (request.getMethod().equals(HttpMethod.POST.name())) {
                MultiReadHttpServletRequest multiReadHttpServletRequest = new MultiReadHttpServletRequest(request);
                log.info("IP:{}, Method:{}, URI:{} Body:{}", request.getRemoteAddr(), request.getMethod(), request.getRequestURI() + query, multiReadHttpServletRequest.getRequestBody());
                chain.doFilter(multiReadHttpServletRequest, response);
            } else {
                log.info("IP:{}, Method:{}, URI:{}", request.getRemoteAddr(), request.getMethod(), request.getRequestURI() + query);
                chain.doFilter(request, response);
            }
        } finally {
            MDC.clear();
        }
    }

    /**
     * HttpServletRequest Request body multi read
     */
    class MultiReadHttpServletRequest extends HttpServletRequestWrapper {

        // Cache RequestBody
        private String requestBody;

        MultiReadHttpServletRequest(HttpServletRequest request) {
            super(request);
            requestBody = "";
            try {
                StringBuilder stringBuilder = new StringBuilder();
                InputStream inputStream = request.getInputStream();
                byte[] bs = new byte[1024];
                int len;
                while ((len = inputStream.read(bs)) != -1) {
                    stringBuilder.append(new String(bs, 0, len));
                }
                requestBody = stringBuilder.toString();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public ServletInputStream getInputStream() throws IOException {
            final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(requestBody.getBytes());

            return new ServletInputStream() {
                public int read() throws IOException {
                    return byteArrayInputStream.read();
                }

                @Override
                public boolean isFinished() {
                    return byteArrayInputStream.available() == 0;
                }

                @Override
                public boolean isReady() {
                    return true;
                }

                @Override
                public void setReadListener(ReadListener readListener) {

                }
            };
        }

        @Override
        public BufferedReader getReader() throws IOException {
            return new BufferedReader(new InputStreamReader(this.getInputStream()));
        }

        String getRequestBody() {
            return requestBody.replaceAll("\n", "");
        }
    }

}

3. Configure log Pattern

logging:
  pattern:
    console: "%d{yyyy-MM-dd HH:mm:ss.SSS} %5p [%15.15t] %-40.40c{1.} [%X{user}] : %m%n%xwEx"
Description: MDC. Put ("user", request. Getremoteuser()); = >% X {user}

Copyright belongs to the author. Please contact the author for reprint or content cooperation

Spring Boot custom parent quick build application

Spring Boot containerized deployment Docker

How to configure https in SpringBot

Spring Boot log processing are you still using Logback?

[behind the double 11 Carnival] how does the micro service registration center carry tens of millions of visits to large-scale systems?

Spring Boot new generation monitoring you should play like this

Spring Boot exception handling

Spring Boot configuration - configuration information encryption

Reject black box application - visual monitoring of Spring Boot application

There are three sources of concurrent bugs. Please open your eyes to see them

This article is based on the platform of blog one article multiple sending OpenWrite Release!

Tags: Java Spring Lombok log4j

Posted on Sat, 09 Nov 2019 06:01:50 -0800 by burhankhan