项目中打印出sql的log,包括执行时间(log4jdbc)

在项目中想知道每个sql的执行时间,从网上搜了下log4jdbc的使用,感觉还挺好用的,很简单的就能集成进来

1.因为是maven项目:引入对应依赖:

<dependency>
    <groupId>org.bgee.log4jdbc-log4j2groupId>
    <artifactId>log4jdbc-log4j2-jdbc4.1artifactId>
    <version>1.16version>
dependency>

2.对应的数据库的配置如下:

driver=net.sf.log4jdbc.sql.jdbcapi.DriverSpy
url=jdbc:log4jdbc:mysql://10.135.106.240:3306/dev

3.在classpath目录下新增配置文件log4jdbc.log4j2.properties

    并配置:

log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
4.因目前项目log用的是logback,在logback的配置文件中logback.xml中配置:

<appender name="FILEINFO"
          class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>logs/telematics/tsgp/tcmp/biz/tcmp-info.logfile>
    <filter class="ch.qos.logback.classic.filter.LevelFilter">
        <level>INFOlevel>
        <onMatch>ACCEPTonMatch>
        <onMismatch>DENYonMismatch>
    filter>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        
        <fileNamePattern>logs-archive/telematics/tsgp/tcmp/biz/tcmp-info-%d{yyyy-MM-dd}.%i.logfileNamePattern>
        <timeBasedFileNamingAndTriggeringPolicy
                class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            
            <maxFileSize>10MBmaxFileSize>
        timeBasedFileNamingAndTriggeringPolicy>
    rollingPolicy>

    <encoder>
        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%npattern>
        <charset class="java.nio.charset.Charset">UTF-8charset>
    encoder>
appender>

<root level="INFO">
    
    <appender-ref ref="FILEINFO"/>
root>


<logger name="jdbc.sqltiming" level="info"/>
<logger name="jdbc.sqlonly" level="ERROR"/>
<logger name="jdbc.audit" level="ERROR"/>
<logger name="jdbc.resultset" level="ERROR"/>
<logger name="jdbc.resultsettable" level="ERROR"/>
<logger name="jdbc.connection" level="ERROR"/>


然后重启项目就生效了,在对应的log文件中可以看到每个sql的执行时间

你可能感兴趣的:(java)