现象1:
mybatis版本:3.0.5
logback配置:
<logger name="com.apache.ibatis" level="DEBUG" />
<logger name="java.sql.Connection" level="DEBUG" />
<logger name="java.sql.Statement" level="DEBUG" />
<logger name="java.sql.PreparedStatement" level="DEBUG" />
正常打印日志。
现象2:
mybatis版本:3.2+
logback配置:
<logger name="com.apache.ibatis" level="DEBUG" />
<logger name="java.sql.Connection" level="DEBUG" />
<logger name="java.sql.Statement" level="DEBUG" />
<logger name="java.sql.PreparedStatement" level="DEBUG" />
不正常打印sql日志
源码分析:
mybatis版本:3.0.5
查看类PreparedStatementLogger:
public Object invoke(Object proxy, Method method, Object[] params) throws Throwable {
try {
if (EXECUTE_METHODS.contains(method.getName())) {
if (log.isDebugEnabled()) {
log.debug("==> Executing: " + removeBreakingWhitespace(sql));
log.debug("==> Parameters: " + getParameterValueString());
}
clearColumnInfo();
if ("executeQuery".equals(method.getName())) {
ResultSet rs = (ResultSet) method.invoke(statement, params);
if (rs != null) {
return ResultSetLogger.newInstance(rs);
} else {
return null;
...
这里log是 “PreparedStatement.class”:
private static final Log log = LogFactory.getLog(PreparedStatement.class);
所以只要配置了PreparedStatement类的级别为DEBUG就可以打印PreparedStatement日志:
<logger name="java.sql.PreparedStatement" level="DEBUG" />
mybatis版本:3.2+
查看类ConnectionLogger:
public Object invoke(Object proxy, Method method, Object[] params) throws Throwable {
try {
if (EXECUTE_METHODS.contains(method.getName())) {
if (log.isDebugEnabled()) {
log.debug("==> Executing: " + removeBreakingWhitespace(sql));
log.debug("==> Parameters: " + getParameterValueString());
}
....
其中log为:
protected boolean isDebugEnabled() {
return statementLog.isDebugEnabled();
}
注意这里的statementLog,看SimpleExecutor的prepareStatement(handler, ms.getStatementLog())
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds,ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
Statement stmt = null;
try {
Configuration configuration = ms.getConfiguration();
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds,resultHandler, boundSql);
stmt = prepareStatement(handler, ms.getStatementLog());
return handler.<E>query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
这个statementLog是ms.getStatementLog()而来的。而MappedStatement的StatementLog
String logId = id; if (configuration.getLogPrefix() != null)
logId = configuration.getLogPrefix() + id;
mappedStatement.statementLog = LogFactory.getLog(logId);
这里可以看到,logPrefix决定了所有log前缀,所以只需要配置logPrefix就行了。
总结:
mybatis版本:3.2+版本的需要配置:###
在mybatis的configuration中增加setting配置
<settings>
<setting name="logPrefix" value="dao."/>
</settings>
然后增加配置
<logger name="dao" level="DEBUG"/>