Spring 핵심원리 고급편 - Logging Filter
목차 Post not found: springboot/spring-aop/log-trace/log-trace-01 Post not found: springboot/spring-aop/log-trace/log-trace-02 Post not found: springboot/spring-aop/log-trace/log-trace-03 Spring 핵심원리 고급편 - Logging FilterTraceId - 트랜잭션 Id와 level을 관리public class TraceId { private String id; // 트랜잭션 ID private int level; // 깊이를 표현할 수 있는 Level public TraceId() { this.id = creatId(); this.level = 0; } private TraceId(String id, int level){ this.id = id; this.level = level; } public String creatId() { return UUID.randomUUID().toString().substring(0, 8); } public TraceId createNextId(){ return new TraceId(id, level+1); } // 트랜잭션 ID 는 기존과 같고 Level 은 하나 감소시킨다. public TraceId createPreviousId(){ return new TraceId(id, level-1); } public boolean isFirstLevel(){ return level == 0; }} TraceStatus - 로그 상태 정보를 나타낸다. traceId 내부에 트랜잭션 Id 와 Level 을 가지고 있다. startTimeMs 로그 시작 시간이다. 로그 종료시 이 시작 시간을 기준으로 시작 ~ 종료까지 수행시간을 구할 수 있다. message 시작시 사용한 메시지다. 로그 종료시에 사용해 출력한다. public class TraceStatus { private TraceId traceId; private Long startTimeMs; private String message; public TraceStatus(TraceId traceId, Long startTimeMs, String message) { this.traceId = traceId; this.startTimeMs = startTimeMs; this.message = message; } public TraceId getTraceId() { return traceId; } public Long getStartTimeMs() { return startTimeMs; } public String getMessage() { return message; }} @Slf4j@Componentpublic class HelloTraceV1 { private static final String START_PREFIX = "-->"; private static final String COMPLETE_PREFIX = "<--"; private static final String EX_PREFIX = "<X-"; public TraceStatus begin(String message) { TraceId traceId = new TraceId(); Long startTimeMs = System.currentTimeMillis(); log.info("[{}] {}{}", traceId.getId(), addSpace(START_PREFIX, traceId.getLevel()), message); return new TraceStatus(traceId, startTimeMs, message); } public void end(TraceStatus status) { complete(status, null); } public void exception(TraceStatus status, Exception e) { complete(status, e); } private void complete(TraceStatus status, Exception e) { Long stopTimeMs = System.currentTimeMillis(); long resultTimeMs = stopTimeMs - status.getStartTimeMs(); TraceId traceId = status.getTraceId(); if (e == null) { log.info("[{}] {}{} time={}ms", traceId.getId(), addSpace(COMPLETE_PREFIX, traceId.getLevel()), status.getMessage(), resultTimeMs); } else { log.info("[{}] {}{} time={}ms ex={}", traceId.getId(), addSpace(EX_PREFIX, traceId.getLevel()), status.getMessage(), resultTimeMs, e.toString()); } } private static String addSpace(String prefix, int level) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < level; i++) { sb.append((i == level - 1) ? "|" + prefix : "| "); } return sb.toString(); }} 테스트 코드 작성