標籤:mybatis的mapper介面加入log4j日誌
配置Log4J比較簡單, 比如需要記錄這個mapper介面的日誌:
package org.mybatis.example;public interface BlogMapper { @Select("SELECT * FROM blog WHERE id = #{id}") Blog selectBlog(int id);}
只要在應用的classpath中建立一個名稱為log4j.properties的檔案, 檔案的具體內容如下:
# Global logging configurationlog4j.rootLogger=ERROR, stdout# MyBatis logging configuration...log4j.logger.org.mybatis.example.BlogMapper=TRACE# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
添加以上配置後,Log4J就會把 org.mybatis.example.BlogMapper 的詳細執行日誌記錄下來,對於應用中的其它類則僅僅記錄錯誤資訊。
也可以將日誌從整個mapper介面層級調整到到語句層級,從而實現更細粒度的控制。如下配置只記錄 selectBlog 語句的日誌:
log4j.logger.org.mybatis.example.BlogMapper.selectBlog=TRACE
與此相對,可以對一組mapper介面記錄日誌,只要對mapper介面所在的包開啟日誌功能即可:
log4j.logger.org.mybatis.example=TRACE
某些查詢可能會返回大量的資料,只想記錄其執行的SQL語句該怎麼辦?為此,Mybatis中SQL語 句的記錄層級被設為DEBUG(JDK Logging中為FINE),結果日誌的層級為TRACE(JDK Logging中為FINER)。所以,只要將記錄層級調整為DEBUG即可達到目的:
log4j.logger.org.mybatis.example=DEBUG
要記錄日誌的是類似下面的mapper檔案而不是mapper介面又該怎麼呢?
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="org.mybatis.example.BlogMapper"> <select id="selectBlog" resultType="Blog"> select * from Blog where id = #{id} </select></mapper>
對這個檔案記錄日誌,只要對命名空間增加日誌記錄功能即可:
log4j.logger.org.mybatis.example.BlogMapper=TRACE
進一步,要記錄具體語句的日誌可以這樣做:
log4j.logger.org.mybatis.example.BlogMapper.selectBlog=TRACE
設定檔log4j.properties的餘下內容是針對日誌格式的,這一內容已經超出本 文檔範圍。關於Log4J的更多內容,可以參考Log4J的網站。
本文出自 “matengbing” 部落格,請務必保留此出處http://matengbing.blog.51cto.com/11395502/1875793
mybatis的mapper介面加入Log4j日誌