HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🌚
[New] 우기팀
/
SQL 쿼리+파라미터 로그 남기기

SQL 쿼리+파라미터 로그 남기기

간단 요약 / 비고
작성일
May 11, 2022
작성자
기술 태그
SpringBoot
JPA

SQL 포맷팅 옵션

  • SQL 쿼리를 보기 좋게 포맷팅 해주는 옵션
application.yml
spring: jpa: properties: hibernate: format_sql: true
insert into member (username, id) values (?, ?)
위의 SQL문을 다음과 같이 포맷팅 해줌
insert into member (username, id) values (?, ?)

1. 첫번째 방법 - 비추

application.yml
spring: jpa: properties: hibernate: show_sql: true # System.out으로 SQL문 출력 - 비추

2. 두번째 방법

application.yml
logging.level: org.hibernate.SQL: debug # 로거를 통한 출력 org.hibernate.type: trace # 파라미터 까지 출력

3. 세번째 방법 - 외부 라이브러리 사용

  • 개발할 때만 쓰거나, 운영 시 성능 테스트 해보고 사용할 것
  • 스프링부트 2.6.7에서는 P6spy 1.8.0 버전 사용
  • https://github.com/gavlyukovskiy/spring-boot-data-source-decorator

P6spy

build.gradle
// <https://mvnrepository.com/artifact/com.github.gavlyukovskiy/p6spy-spring-boot-starter> implementation 'com.github.gavlyukovskiy:p6spy-spring-boot-starter:1.8.0'
아래와 같이 파라미터까지 로그 찍어줌
insert into member (username, id) values (?, ?) insert into member (username, id) values ('memberA', 1);
 

3.1 P6spy 사용 시 로그 커스텀 하는법

기본 등록만 하니까 ? 포함 로그가 찍히는게 거슬려서 찾아보니까 로그를 커스텀 하는 방법이 있었습니다.
@)참고 - [JPA] 쿼리 로깅에 p6spy multi line 적용하기
설정 법
import com.p6spy.engine.spy.P6SpyOptions; import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; @Configuration public class P6spyLogMessageFormatConfiguration { @PostConstruct public void setLogMessageFormat() { P6SpyOptions.getActiveInstance().setLogMessageFormat(CustomP6spySqlFormat.class.getName()); } }
설정 파일
import com.p6spy.engine.logging.Category; import com.p6spy.engine.spy.appender.MessageFormattingStrategy; import org.hibernate.engine.jdbc.internal.FormatStyle; import java.util.Locale; public class CustomP6spySqlFormat implements MessageFormattingStrategy { @Override public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) { return formatSql(category, sql); } private String formatSql(String category,String sql) { // 여기 부터 if(sql ==null || sql.trim().equals("")) return sql; // Only format Statement, distinguish DDL And DML if (Category.STATEMENT.getName().equals(category)) { String tmpsql = sql.trim().toLowerCase(Locale.ROOT); if(tmpsql.startsWith("create") || tmpsql.startsWith("alter") || tmpsql.startsWith("comment")) { sql = FormatStyle.DDL.getFormatter().format(sql); }else { sql = FormatStyle.BASIC.getFormatter().format(sql); } } // 여기 까지 주석하면 한줄 출력 return sql; } }
커스텀 sql format
format 파일의 아래 private 메서드가 DDL, DML 제외 select 쿼리에 대해서만 formatting 을 해주는데
formatting 없이 한 줄로 보고 싶으면 그냥 다 주석 처리 하고 return sql 하면 되네요
 
기본 설정에서 처럼 소요된 시간, 커넥션 정보 들을 로그에 포함하고 싶으면 formatMessage 메서드의 여러 파라미터를 조합해서 사용하면 되는것 같습니다.
 
저는 그냥 sql 만 리턴하는 것이 좋은거 같아서 지웠습니다.
자세한 내용은 링크 참고해 주세용👍👍👏
 
비포 애프터
2022-05-19 01:35:38.106 INFO 4134 --- [ main] p6spy : #1652891738106 | took 0ms | statement | connection 3| url jdbc:h2:tcp://localhost/~/querydsl select team0_.id as id1_2_0_, team0_.name as name2_2_0_ from team team0_ where team0_.id=? select team0_.id as id1_2_0_, team0_.name as name2_2_0_ from team team0_ where team0_.id=1;
적용 전 덕지덕지 로그
 
2022-05-19 01:30:16.478 INFO 4118 --- [ main] p6spy : select team0_.id as id1_2_0_, team0_.name as name2_2_0_ from team team0_ where team0_.id=1
적용 결과 multiline o
2022-05-19 01:34:34.529 INFO 4129 --- [ main] p6spy : select team0_.id as id1_2_0_, team0_.name as name2_2_0_ from team team0_ where team0_.id=1
적용 결과 multiline x