Logback MDC(mapped diagnostic contexts) 로 로그파일 분리
Spring 에서 특정 API의 HTTP Request 로그를 별도 파일에 저장하고 싶었다.
검색을 해보니 SiftingAppender 를 이용하여 MDC 의 특정 키값을 사용하는 예제가 있었다.
Slf4j의 org.slf4j.MDC 클래스를 이용하여 키값을 할당할수 있다.
그런데 MDC는 static 이다. 그럼 thread-safe 한가?
다음과 같은 글이 있다.
Advanced Use
Mapped Diagnostic Contexts shine brightest within client server architectures. Typically, multiple clients will be served by multiple threads on the server. Although the methods in the MDC
class are static, the diagnostic context is managed on a per thread basis, allowing each server thread to bear a distinct MDC
stamp. MDC
operations such as put()
and get()
affect only the MDC
of the currentthread, and the children of the current thread. The MDC
in other threads remain unaffected. Given that MDC
information is managed on a per thread basis, each thread will have its own copy of the MDC
. Thus, there is no need for the developer to worry about thread-safety or synchronization when programming with the MDC
because it handles these issues safely and transparently.
thread safe 걱정은 하지말자.
그래도 thread pool 환경에서 적절하게 put 하고 remove/clear 를 해주는게 맞겠다.
여기 까지만 하면 request thread 들어오는 filter 라던지 intercepter 또는
개별적인 api내에 MDC.put(“fileName”, 파일명) 을 지정함으로써
지정한 파일명으로 로그가 쌓이겠다.
흠. 그런데 나는 특정 API에 대해 Http Request 로그를 따로 쌓고 싶었다.
쉽고 , 대상 API가 추가될때도 적용이 쉬운 방법을 생각해봤다.
나의 경우는 특정 API의 Request 정보를 따로 로깅하려는 경우이기 때문에.
@RestContorller 의 API메소드를 구분하기 위해 @RequestLog 라는 어노테이션을 만들고, 이 RequestLog 어노테이션을 pointcut 으로 지정한 Aspect 를 등록했다.
filter 나 인터셉터에서 , HTTP Method, HTTP URI로 조건을 걸어 처리해도 되지만.
해당 API로직에 적용되어 있는게 더 명확해보였다.
단순히 로그를 찍는 Aspect 클래스만 대상으로 로거 설정을 하면 되겠다.
slf4j 나 logback의 로거 설정에 대해 잘 모르기 때문에 어거지로 맞춘 부분도 있다.
이참에 document를 봐봐야겠다.
* 좋은 방법아시면 저한테도 알려주세요.