이전에 p6spy 적용하기 글을 남겼다.
[Spring Data JPA] Spring 3에 p6spy 적용하기
[Spring Data JPA] Spring 3에 p6spy 적용하기
P6spy 적용 이유 - P6Spy를 사용하는 주된 이유는 스프링 부트와 JPA를 사용하는 프로젝트에서 SQL 쿼리를 정확하고 효과적으로 로깅하고 추적하기 위해서이다. P6Spy는 아래의 3가지 상황에서 사용된
taek2.tistory.com
이어서 sql 쿼리를 커스텀해서 가독성이 좋게 포맷하는 과정과, 로그 파일 남기기, 로그 레벨 설정에 대해 알아보겠다.
p6spy Custom format
1. formatter 객체 생성
아키텍처에 따른 패키지에 다음 파일을 생성하고 코드를 작성한다.
<CustomP6spyFormatter.class>
import com.p6spy.engine.logging.Category;
import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
import org.hibernate.engine.jdbc.internal.FormatStyle;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class CustomP6SpyFormatter implements MessageFormattingStrategy {
@Override
public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) {
String formattedTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date(Long.parseLong(now)));
String formattedSql = formatSql(category, sql);
return formattedTime
+ " | " + elapsed + " ms"
+ " | " + category
+ formattedSql;
}
private String formatSql(String category, String sql) {
if (sql != null && !sql.trim().isEmpty() && Category.STATEMENT.getName().equals(category)) {
String trimmedSQL = sql.trim().toLowerCase(Locale.ROOT);
if (trimmedSQL.startsWith("create") || trimmedSQL.startsWith("alter") || trimmedSQL.startsWith("comment")) {
sql = FormatStyle.DDL.getFormatter().format(sql);
} else {
sql = FormatStyle.BASIC.getFormatter().format(sql);
}
return sql;
}
return sql;
}
}
단순하게 hibernate 패키지에서 제공하는 FormatStyle을 사용하여 currentTime 과 sql을 포맷하는 로직을 구성했다.
2. spy.properties에서 CustomP6spyFormatter 설정
<spy.properties>
appender=com.p6spy.engine.spy.appender.Slf4JLogger
logMessageFormat=com.(MyPackagePath).CustomP6spyFormatter
logMessageFormat을 CustomP6spyFormatter로 적용시킨다.
그리고 이제 실행해보자.
sql 쿼리가 기존의 hibernate처럼 포맷되어서 값이 들어간 형태로 출력된다.
가독성이 훨씬 좋아졌다.
로깅
로그 파일과 로그 레벨을 생성을 위한 설정을 하기전에 이제 로깅을 위해 application.yml에 spring.jpa.properties 설정은 지우도록 하자.
1. 로그 파일 생성
<application.yml>
spring:
datasource:
...
jpa:
hibernate:
ddl-auto: update
logging:
file:
name: ../logs/(logFileName).log
decorator:
datasource:
p6spy:
enable-logging: true
logging.file.name 을 추가하고, 로그파일이 생성될 경로는 직접 지정해주면된다.
나는 프로젝트 상위 폴더에 logs 폴더를 만들고 거기에 로그 파일을 남기도록 설정해두었다.
2. 로그 레벨 설정
로그 레벨 설정은 logging.level.(MyPackagePath) : TRACE / DEBUG / INFO / WARN / ERROR 중에 하나 써주면 된다. 내 패키지가 만약 com.study.example이고, 로그 레벨을 debug로 하겠다면, 다음과 같이 써주면된다.
logging:
file:
name: ../logs/(logFileName).log
level:
com.study.example: debug
이렇게 패키지별로 세부적으로 logging 레벨을 설정할 수 있다.
서비스 운영에 가장 중요한것 중 하나가 로그를 남기는 것이다.
보이지 않는곳에서 오류나 버그가 나게되면 추적하기에 가장 좋은 것이 로그 기록이기 때문이다.
시간이 난다면 로그를 남기는 여러가지 방법과 로그 레벨에 대해서 깊게 공부해보고 기록해보도록 해야겠다.
이렇게 p6spy를 사용해서 가독성 좋은 로그 파일을 남겨서 개발 환경이 조금이라도 개선되었으면 하는 마음으로 포스팅을 마친다.
'백엔드 개발 > Spring&JPA' 카테고리의 다른 글
[트러블슈팅] PostgreSQL에서 한국어 정렬(ORDER BY) 문제 해결 방법 - Collation (0) | 2025.02.04 |
---|---|
[Spring Data JPA] 영속성 컨텍스트 (PersistenceContext) (0) | 2024.08.30 |
[Spring Data JPA] Spring boot 3에 p6spy 적용하기 (4) | 2024.08.28 |
[Spring Data JPA] 로그인 기능 구현(3) - JWT 적용 (0) | 2024.06.28 |
[Spring Data JPA] 로그인 기능 구현(2) - Password Encode (0) | 2024.06.25 |