1. 程式人生 > >SSM控制檯列印SQL語句

SSM控制檯列印SQL語句

pom.xml 新增如下依賴

<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.25</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.25</version>
</dependency>

根據你的web路徑在對應下面建立一個log4j.properties檔案 內容如下:

log4j.rootLogger=DEBUG, Console      
#Console    
log4j.appender.Console=org.apache.log4j.ConsoleAppender    
log4j.appender.Console.layout=org.apache.log4j.PatternLayout    
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n      
log4j.logger.java.sql.ResultSet=INFO    
log4j.logger.org.apache=INFO    
log4j.logger.java.sql.Connection=DEBUG    
log4j.logger.java.sql.Statement=DEBUG    
log4j.logger.java.sql.PreparedStatement=DEBUG

然後在Mybatis-config.xml 配置檔案中新增如下:

<settings>
    <!-- 目的是列印查詢語句 -->
    <setting name="logImpl" value="LOG4J" />
</settings>

還有需要在 web.xml中新增如下:

<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/log4j.properties</param-value>
</context-param>

<context-param>
    <param-name>log4jRefreshInterval</param-name>
    <param-value>60000</param-value>
</context-param>
<listener>
    <listener-class>
        org.springframework.web.util.Log4jConfigListener
    </listener-class>
</listener>

需放在監聽之前

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

主要是為了防止出現下面這個錯誤 (載入順序的問題)

log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).
log4j:WARN Please initialize the log4j system properly.

log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

還有一個錯誤是:(大部分皆因版本不一致的原因 仔細對比Maven倉庫的最新版本)

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.