All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.itcoon.common.tracelog.component.HttpTraceLogger Maven / Gradle / Ivy

package com.itcoon.common.tracelog.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itcoon.common.tracelog.config.properties.HttpTraceLogProperties;
import com.itcoon.common.tracelog.enums.LogSegment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

public class HttpTraceLogger implements TraceLogResolver {

    public static final Logger log = LoggerFactory.getLogger(HttpTraceLog.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private HttpTraceLogProperties properties;

    @Override
    public void resolve(HttpTraceLog traceLog){
       List segments =  properties.getSegments();
        StringJoiner joiner = new StringJoiner(",");
        List arguments = new ArrayList<>();
        for (LogSegment segment : segments) {
            if(segment == LogSegment.METHOD){
                joiner.add("method={}");
                arguments.add(traceLog.getMethod());
            }else if(segment == LogSegment.URI){
                joiner.add("uri={}");
                arguments.add(traceLog.getPath());
            }else if(segment == LogSegment.PARAMETER && traceLog.getParameterMap() != null){
                joiner.add("parameter={}");
                StringJoiner parameterJoiner = new StringJoiner(",");
                for (Map.Entry entry : traceLog.getParameterMap().entrySet()) {
                   parameterJoiner.add("{" + entry.getKey() + ":" + Arrays.toString(entry.getValue()) + "}");
                }
                arguments.add("[" + parameterJoiner + "]");
            } else if (segment == LogSegment.REQUEST_BODY && traceLog.getRequestBody() != null) {
                joiner.add("requestBody={}");
                arguments.add(traceLog.getRequestBody());
            } else if (segment == LogSegment.RESPONSE_BODY && traceLog.getResponseBody() != null) {
                joiner.add("responseBody={}");
                arguments.add(traceLog.getResponseBody());
            } else if (segment == LogSegment.HEADER && traceLog.getHeaderMap() != null) {
                joiner.add("header={}");
                arguments.add(traceLog.getHeaderMap());
            } else if (segment == LogSegment.DURATION) {
                joiner.add("timeTaken={}");
                arguments.add(traceLog.getTimeTaken());
            } else if (segment == LogSegment.USER_IP && traceLog.getUserIp() != null) {
                joiner.add("userIp={}");
                arguments.add(traceLog.getUserIp());
            } else if (segment == LogSegment.STATUS) {
                joiner.add("status={}");
                arguments.add(traceLog.getStatus());
            }
        }
        log.info("Http trace log: " + joiner, arguments.toArray());
    }
}