티스토리 뷰

카테고리 없음

Spring boot AOP 로깅

Grand_J 2024. 1. 19. 09:07
반응형

 

Spring boot AOP 로깅 

@Slf4j
@Aspect
@Component
public class LogAspect {

    @Autowired
    private JwtUtils jwtUtils;

    @Around("execution( * com.xxx.api.domain..controller..*(..)) && args(.., @RequestBody requestBody)")
    public Object logging(ProceedingJoinPoint pjp, Object requestBody) {

        Object result = null;

        try {
            long startAt = System.currentTimeMillis();
            result = pjp.proceed();
            long endAt = System.currentTimeMillis();
            log.info("### API-CALL : {} ({}ms) ", getRequestData(pjp, requestBody), (endAt-startAt));
        } catch (Throwable e) {
            log.info(e.getMessage());
            throw new CommonRuntimeException(ResponseCode.LOGGING_ERROR);
        }
        return result;
    }

    private String getRequestData(ProceedingJoinPoint pjp, Object requestBody) {

        Map<String, Object> dataMap = new LinkedHashMap<>();

        RequestAttributes requestAttribute = RequestContextHolder.getRequestAttributes();

        if(requestAttribute != null){
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes()).getRequest();

            dataMap.put("uri", request.getRequestURI());
            dataMap.put("method", request.getMethod());
            dataMap.put("controller", pjp.getSignature().getDeclaringType().getSimpleName());
            dataMap.put("access_token", jwtUtils.getAccessToken());
            // dataMap.put("param", this.paramToMap(request.getParameterMap()));
            dataMap.put("body", this.requestBodyToMap(requestBody));

        }

        return mapToJson(dataMap);

    }

    private Map<String, Object> paramToMap(Map<String, String[]> paramMap) {
        Map<String, Object> dataMap = new LinkedHashMap<>();
        paramMap.forEach((key, value) -> {
            String values = String.join("", value);
            dataMap.put(key, values);
        });
        return dataMap;
    }

    private Map<String, Object> requestBodyToMap(Object requestBody) {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> dataMap = objectMapper.registerModule(new JavaTimeModule()).convertValue(requestBody, Map.class);
        return dataMap;
    }

    private String mapToJson(Map<String, Object> dataMap){
        String data = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            data = objectMapper.writeValueAsString(dataMap);

        } catch (JsonProcessingException e) {
            log.error("mapToJson ::: Redis Object Set Error");
        }
        return data;
    }

}

 

 

 

끗!@#$!@#$!

반응형