티스토리 뷰
로그 기록
Log4j
로깅 유틸리티 Log4j
Log4j의 구조와 로깅 레벨
1.logger
2.appender
3.layout
로그 환경 설정 파일의 구성
인터셉터
인터셉터
인터셉터 등록
인터셉터를 이용한 로그 기록
HandlerInterceptor
HandlerInterceptor를 사용해 로그 기록하기
pom.xml
log4j.xml
MonitoringInterceptor.java
package com.springmvc.interceptor;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StopWatch;
import org.springframework.web.servlet.HandlerInterceptor;
public class MonitoringInterceptor implements HandlerInterceptor{
ThreadLocal<StopWatch> stopWatchLocal = new ThreadLocal<StopWatch>();
public Logger logger = LoggerFactory.getLogger(this.getClass());
public boolean preHandle
(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception
{
StopWatch stopWatch = new StopWatch(handler.toString());
stopWatch.start(handler.toString());
stopWatchLocal.set(stopWatch);
logger.info("접근한 URI 경로 :" + getURLPath(request) );
logger.info("요청 처리 시작 시간 : "+ getCurrentTime());
return true;
}
private String getCurrentTime() {
// TODO Auto-generated method stub
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
return formatter.format(calendar.getTime());
}
private String getURLPath(HttpServletRequest request) {
// TODO Auto-generated method stub
String currentPath = request.getRequestURI();
String queryString = request.getQueryString();
queryString = queryString == null ? "" : "?" + queryString;
return currentPath + queryString;
}
public void postHandle(HttpServletRequest arg0, HttpServletResponse response,
Object handler,Exception exception) throws Exception
{
StopWatch stopWatch = stopWatchLocal.get();
stopWatch.stop();
logger.info("요청 처리 소요 시간 : "+ stopWatch.getTotalTimeMillis() + "ms");
stopWatchLocal.set(null);
logger.info("======================");
}
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception exception) throws Exception
{
StopWatch stopWatch = stopWatchLocal.get();
stopWatch.stop();
logger.info("요청 처리 소요 시간 : " + stopWatch.getTotalTimeMillis() + "ms");
stopWatchLocal.set(null);
logger.info("====================================");
}
}
servlet-context.xml
파일로 로그 기록 출력하기
'정리 노트 > Spring' 카테고리의 다른 글
Spring Chapter13 [16-5] (0) | 2024.01.26 |
---|---|
Spring Chapter11~Chapter12 [16-3] (0) | 2024.01.25 |
Spring Chapter9~Chapter10[16-2] (0) | 2024.01.24 |
Spring Chapter8 [16-1] (0) | 2024.01.22 |
Spring Chapter7 [15-5] (0) | 2024.01.19 |