SpringBoot之JdbcTemplate输出完整SQL日志

发布于:2024-04-23 ⋅ 阅读:(151) ⋅ 点赞:(0)

applicatio.yml开启日志功能

jdbc-log:
  # 开启完整SQL日志输出功能
  enabled: true

logging:
  level:
  	# 切面类路径,日志级别为DEBUG,因为SpringBoot默认日志级别为INFO
    com.xxx.xxx.JdbcTemplateAspect: DEBUG

日志切面

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Objects;

@Slf4j
@Aspect
@Component
@ConditionalOnProperty(prefix = "jdbc-log", value = "enabled", havingValue = "true")
public class JdbcTemplateAspect {
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
	
	//执行切面前,输出完整SQL,防止执行SQL过程中报错,导致无法输出完整SQL。
    @Before(value = "execution(* org.springframework.jdbc.core.JdbcTemplate.*(..))")
    public void afterQuery(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        if (ArrayUtils.isNotEmpty(args) && args[0] instanceof String && args[2] instanceof Object[]) {
            String sql = ((String) args[0]).replaceAll("[\\s\\n\\t]+", " ");
            Object[] params = (Object[]) args[2];
            for (Object propertyValue : params) {
                String value;
                if (Objects.isNull(propertyValue)) {
                    value = "null";
                    sql = sql.replaceFirst("\\?", value);
                    continue;
                }
                if (propertyValue instanceof String) {
                    value = "'" + propertyValue + "'";
                } else if (propertyValue instanceof Date) {
                    value = "'" + DATE_TIME_FORMATTER.format(((Date) propertyValue).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()) + "'";
                } else if (propertyValue instanceof LocalDate) {
                    value = "'" + DATE_FORMATTER.format((LocalDate) propertyValue) + "'";
                } else if (propertyValue instanceof LocalDateTime) {
                    value = "'" + DATE_TIME_FORMATTER.format((LocalDateTime) propertyValue) + "'";
                } else {
                    value = propertyValue.toString();
                }
                sql = sql.replaceFirst("\\?", value);
            }
            log.debug("\033[32mexecute SQL:\n{}\033[0m", sql);
        }
    }
}

启动项目,调用某个JdbcTemplate类里面的方法就会输出完整SQL到控制台,如下内容

execute SQL:
select * from table where id=1

网站公告

今日签到

点亮在社区的每一天
去签到