package com.mingzuozhibi.commons.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.Stream.Builder;

@Slf4j
public abstract class LoggerUtils {

    public static void logRequestIfExists() {
        var attributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = attributes != null ? attributes.getRequest() : null;
        if (request == null) return;
        String params = request.getParameterMap().entrySet().stream()
            .map(e -> e.getKey() + "=" + printValue(e.getValue()))
            .collect(Collectors.joining(", ", "{", "}"));
        String headers = streamOf(request.getHeaderNames())
            .map(key -> key + "=" + printValue(request.getHeaders(key)))
            .collect(Collectors.joining(", ", "{", "}"));
        log.debug("Request: uri=%s %s, params=%s, headers=%s".formatted(
            request.getMethod(), request.getRequestURI(), params, headers
        ));
    }

    private static <E> Stream<E> streamOf(Enumeration<E> enumeration) {
        Builder<E> builder = Stream.builder();
        while (enumeration.hasMoreElements()) {
            builder.add(enumeration.nextElement());
        }
        return builder.build();
    }

    private static String printValue(Enumeration<String> headers) {
        return printValue(streamOf(headers).toList().toArray(new String[0]));
    }

    private static String printValue(String[] value) {
        return value.length == 1 ? value[0] : Arrays.toString(value);
    }

}

@@ -278,44 +278,9 @@
 til.
-Arrays;%0Aimport java.util.Enumeration
+*
 ;%0Aim
@@ -488,25 +488,28 @@
     
-var attributes = 
+Optional.ofNullable(
 ((Se
@@ -576,17 +576,17 @@
 butes())
-;
+)
 %0A       
@@ -586,20 +586,25 @@
         
-Http
+    .map(
 ServletR
@@ -613,108 +613,142 @@
 uest
- request = attributes != null ? attributes.getRequest() : null;%0A        if (request == null) return;
+Attributes::getRequest).ifPresent(LoggerUtils::printRequest);%0A    %7D%0A%0A    public static void printRequest(HttpServletRequest request) %7B
 %0A   

Update logRequestIfExists