該文中使用的log框架爲logbackjava
myBatis3.0.6左右的版本時sql
打印sql的時候只須要配置以下屬性:mybatis
<logger name="java.sql.Connection" level="DEBUG" /> <logger name="java.sql.Statement" level="DEBUG" /> <logger name="java.sql.PreparedStatement" level="DEBUG" />
源碼解析:app
PreparedStatementLogger裏面看這個log.isDebugEnabled()框架
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; } } else { return method.invoke(statement, params); } }this
這個log定義的是PreparedStatementspa
private static final Log log = LogFactory.getLog(PreparedStatement.class);
在myBatis3.2.7左右版本debug
更改了打印Sql的模式,它將sql打印細化到了每個mapperStatement的每個方法上。code
若是你打算有一個全局配置打印全部的sql,則須要以下配置rem
在mybatis的configuration中增長setting配置
<settings> <setting name="logPrefix" value="dao."/> </settings>
而後增長配置
<logger name="dao" level="DEBUG"/>
源碼解析:
ConnectionLogger
public Object invoke(Object proxy, Method method, Object[] params) throws Throwable { try { if (Object.class.equals(method.getDeclaringClass())) { return method.invoke(this, params); } if ("prepareStatement".equals(method.getName())) { if (isDebugEnabled()) { debug(" Preparing: " + removeBreakingWhitespace((String) params[0]), true); } PreparedStatement stmt = (PreparedStatement) method.invoke(connection, params); stmt = PreparedStatementLogger.newInstance(stmt, statementLog, queryStack); return stmt; }
其中的isDebugEnabled()指的是
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就好了