FieldLogTrace 스프링에 빈으로 등록해야 한다.
@Configuration
public class LogTraceConfig {
@Bean
public LogTrace logTrace() {
return new FieldLogTrace(); //싱글톤으로 등록
}
}
package study.advanced.app.v3;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.RequiredArgsConstructor;
import study.advanced.trace.TraceStatus;
import study.advanced.trace.logtrace.LogTrace;
@RestController
@RequiredArgsConstructor
public class OrderControllerV3 {
private final OrderServiceV3 orderService;
private final LogTrace trace;
@GetMapping("/v3/request") //요청이 오면 아래 메서드가 호출
public String request(String itemId) {
TraceStatus status = null;
//예외가 되더라도 로그가 되게끔 try처리
try {
status = trace.begin("OrderController.request()");
orderService.orderItem(itemId);
trace.end(status);
return "ok";
}catch (Exception e) {
trace.exception(status, e);
throw e; // 예외를꼭 다시 던져주어야 한다.
}
}
}
package study.advanced.app.v3;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import study.advanced.trace.TraceStatus;
import study.advanced.trace.logtrace.LogTrace;
@Service
@RequiredArgsConstructor
public class OrderServiceV3 {
private final OrderRepositoryV3 orderRepository;
private final LogTrace trace;
public void orderItem(String itemId) {
TraceStatus status = null;
// 예외가 되더라도 로그가 되게끔 try처리
try {
status = trace.begin("OrderService.orderItem()");
orderRepository.save(itemId);
trace.end(status);
} catch (Exception e) {
trace.exception(status, e);
throw e;
}
}
}
package study.advanced.app.v3;
import org.springframework.stereotype.Repository;
import lombok.RequiredArgsConstructor;
import study.advanced.trace.TraceStatus;
import study.advanced.trace.logtrace.LogTrace;
@Repository
@RequiredArgsConstructor
public class OrderRepositoryV3 {
private final LogTrace trace;
public void save(String itemId) {
TraceStatus status = null;
try {
status = trace.begin("OrderRepository.save()");
//저장로직
if(itemId.equals("ex")) {
throw new IllegalStateException("예외발생");
}
//상품저장에 1초
sleep(1000);
trace.end(status);
}catch(Exception e) {
trace.exception(status, e);
throw e;
}
}
private void sleep(int millis) {
try {
Thread.sleep(millis);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
로그가 제대로 나오는걸 확인할 수 있다.!