Home  >  Article  >  Java  >  How SpringBoot integrates P6Spy to implement SQL logging

How SpringBoot integrates P6Spy to implement SQL logging

WBOY
WBOYforward
2023-05-15 12:10:061182browse

P6Spy Introduction

P6Spy is an open source framework that can be used to intercept and modify data manipulation statements in applications.

SQL statements can be intercepted through P6Spy, which is equivalent to a recorder of SQL statements, so that we can use it for related analysis, such as performance analysis.

Application scenario

pom


        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            com.alibaba
            druid-spring-boot-starter
            1.1.20
        
        
            mysql
            mysql-connector-java
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.1.1
        
        
            org.projectlombok
            lombok
        
        
            p6spy
            p6spy
            3.8.2
        
        
            com.alibaba
            fastjson
            1.2.83
        
    

application.yml

spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
#driver-class-name: com.p6spy.engine.spy.P6SpyDriver
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql ://localhost:3306/course_db?serverTimezone=GMT+8
# url: jdbc:p6spy:mysql://localhost:3306/course_db?serverTimezone=GMT+8
username: root
password: root

# Open the sql log output of mybatis-plus
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

entity

@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("course_1")
public class Course {
    @TableField("cid")
    private Long cId;
    private String cName;
    private Integer userId;
    private String cStatus;
}

Mapper

public interface CourseMapper extends BaseMapper {
}

Startup class

@SpringBootApplication
@MapperScan(basePackages = "cn.zysheep.mapper")
public class ShardingjdbcdemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(ShardingjdbcdemoApplication.class, args);
    }
}

Test class

@SpringBootTest
@Slf4j
class ShardingjdbcdemoApplicationTests {
    @Autowired
    private CourseMapper courseMapper;
    @SneakyThrows
    @Test
    void findCourse() {
        courseMapper.selectList(null).forEach(System.out::println);
    }
}

mybatis-plus can also be used The printed sql log is not the effect we want. How to control the desired sql log output can be done by using the P6Spy open source product.

How SpringBoot integrates P6Spy to implement SQL logging

Getting started with P6Spy

spy.properties

resources Add a configuration file to the directory, similar to log4j .xml, record configuration information

module.log=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# sql log printout
# 1. logMessageFormat=com.p6spy.engine.spy.appender.SingleLineFormat
# 2. logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
# customLogMessageFormat=%(currentTime) | SQL use time: %(executionTime) ms | connect info: %(category)-%(connectionId) | execute sql: %(sql)
# 3. Custom log printing (fully qualified class name)
logMessageFormat=cn .zysheep.config.P6SPYConfig
# Use the log system to record sql
appender=com.p6spy.engine.spy.appender.Slf4JLogger
## Configure logging Log exceptions
excludecategories=info,debug,result ,batc,resultset
# Set to use p6spy driver as proxy
deregisterdrivers=true
# Date format
dateformat=yyyy-MM-dd HH:mm:ss
# Actual driver
driverlist=com.mysql.cj.jdbc.Driver
# Whether to enable slow SQL logging
outagedetection=true
# Slow SQL logging standard seconds
outagedetectioninterval=2

P6Spy has a built-in SQL output format, as shown in the configuration file above. Here we use custom SQL log printing

P6SPYConfig

public class P6SPYConfig  implements MessageFormattingStrategy {
    @Override
    public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) {
        Map message = new LinkedHashMap<>(8);
        String newPrepared = prepared.replace("   ", "").replace("\n", " ");
        message.put("prepared", newPrepared);
        String newSql = sql.replace("   ", "").replace("\n", " ");
        message.put("sql", newSql);
        return JSONObject.toJSONString(message, true);
    }
}

application.yml

spring:
datasource:
# driver-class-name : com.mysql.cj.jdbc.Driver
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
type: com.alibaba.druid.pool.DruidDataSource
# url: jdbc: mysql://localhost:3306/course_db?serverTimezone=GMT+8
url: jdbc:p6spy:mysql://localhost:3306/course_db?serverTimezone=GMT+8
username: root
password: root

# Open the sql log output of mybatis-plus
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

The test class remains unchanged

How SpringBoot integrates P6Spy to implement SQL logging

The above is the detailed content of How SpringBoot integrates P6Spy to implement SQL logging. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete