debug模式下mybatis经常看到会输出很多数据库操作相关的日志,这里其实使用到了mybatis内置的的一个日志框架。目前主流的日志框架mybatis基本上都支持,阅读过源码的人可能会发现其实mybatis使用了适配器的设计模式为每一种开源的日志框架做了一层适配层。具体原码对应的包结构如下
1. 日志工厂org.apache.ibatis.logging.LogFactory
1.1 mybatis会自己配置一下加载开源日志类的一个顺序,一旦加载成功则后续mybatis就是用这个日志框架
以slf4日志框架为例,调用方调用org.apache.ibatis.logging.LogFactory#getLog(java.lang.String)
获取日志处理类Log
private static Constructor extends Log> logConstructor;
static {
tryImplementation(LogFactory::useSlf4jLogging);
tryImplementation(LogFactory::useCommonsLogging);
tryImplementation(LogFactory::useLog4J2Logging);
tryImplementation(LogFactory::useLog4JLogging);
tryImplementation(LogFactory::useJdkLogging);
tryImplementation(LogFactory::useNoLogging);
}
private static void tryImplementation(Runnable runnable) {
if (logConstructor == null) {
try {
runnable.run();
} catch (Throwable t) {
// ignore
}
}
}
public static synchronized void useSlf4jLogging() {
setImplementation(org.apache.ibatis.logging.slf4j.Slf4jImpl.class);
}
private static void setImplementation(Class extends Log> implClass) {
try {
Constructor extends Log> candidate = implClass.getConstructor(String.class);
Log log = candidate.newInstance(LogFactory.class.getName());
if (log.isDebugEnabled()) {
log.debug("Logging initialized using '" + implClass + "' adapter.");
}
logConstructor = candidate;
} catch (Throwable t) {
throw new LogException("Error setting Log implementation. Cause: " + t, t);
}
}
public static Log getLog(String logger) {
try {
return logConstructor.newInstance(logger);
} catch (Throwable t) {
throw new LogException("Error creating logger for logger " + logger + ". Cause: " + t, t);
}
}
2. mybatis内置log接口org.apache.ibatis.logging.Log
2.1 mybatis预实现的外部开源log实现类
- org.apache.ibatis.logging.slf4j.Slf4jImpl
- org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl
- org.apache.ibatis.logging.log4j2.Log4j2Impl
- org.apache.ibatis.logging.log4j.Log4jImpl
- org.apache.ibatis.logging.jdk14.Jdk14LoggingImpl
- org.apache.ibatis.logging.nologging.NoLoggingImpl
2.2 slf4j日志实现类分析org.apache.ibatis.logging.slf4j.Slf4jImpl
首先Slf4jImpl实现了Log接口,通过外部传递的class类获取slf4j的日志类,如果对应的slf4j日志实现类有多了则通过适配器模式就创建多个适配器
public Slf4jImpl(String clazz) {
Logger logger = LoggerFactory.getLogger(clazz);
if (logger instanceof LocationAwareLogger) {
try {
// check for slf4j >= 1.6 method signature
logger.getClass().getMethod("log", Marker.class, String.class, int.class, String.class, Object[].class, Throwable.class);
log = new Slf4jLocationAwareLoggerImpl((LocationAwareLogger) logger);
return;
} catch (SecurityException | NoSuchMethodException e) {
// fail-back to Slf4jLoggerImpl
}
}
// Logger is not LocationAwareLogger or slf4j version < 1.6
log = new Slf4jLoggerImpl(logger);
}
2.3 jdbc操作语句日志实现
mybatis针对需要打印日志的操作对象其实使用过代理的模式创建对应的包含打印日志功能的代理类
- org.apache.ibatis.logging.jdbc.ConnectionLogger
- org.apache.ibatis.logging.jdbc.PreparedStatementLogger
- org.apache.ibatis.logging.jdbc.ResultSetLogger
- org.apache.ibatis.logging.jdbc.StatementLogger
2.3.1 jdbc操作日志代理类创建流程
2.3.1.1 ConnectionLogger 创建
1) org.apache.ibatis.executor.BaseExecutor#getConnection
当创建connection的时候如果日志开启debug模式的话,则通过代理模式创建对应的代理类ConnectionLogger,具体代码如下
protected Connection getConnection(Log statementLog) throws SQLException {
Connection connection = transaction.getConnection();
if (statementLog.isDebugEnabled()) {
return ConnectionLogger.newInstance(connection, statementLog, queryStack);
} else {
return connection;
}
}
public static Connection newInstance(Connection conn, Log statementLog, int queryStack) {
InvocationHandler handler = new ConnectionLogger(conn, statementLog, queryStack);
ClassLoader cl = Connection.class.getClassLoader();
return (Connection) Proxy.newProxyInstance(cl, new Class[]{Connection.class}, handler);
}
2.3.1.2 PreparedStatementLogger和StatementLogger 创建
1) org.apache.ibatis.logging.jdbc.ConnectionLogger#invoke
当通过connection获取statement的时候,通过代理模式创建对应的代理类
- PreparedStatementLogger.newInstance(stmt, statementLog, queryStack);
- StatementLogger.newInstance(stmt, statementLog, queryStack);
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()) || "prepareCall".equals(method.getName())) {
if (isDebugEnabled()) {
debug(" Preparing: " + removeExtraWhitespace((String) params[0]), true);
}
PreparedStatement stmt = (PreparedStatement) method.invoke(connection, params);
stmt = PreparedStatementLogger.newInstance(stmt, statementLog, queryStack);
return stmt;
} else if ("createStatement".equals(method.getName())) {
Statement stmt = (Statement) method.invoke(connection, params);
stmt = StatementLogger.newInstance(stmt, statementLog, queryStack);
return stmt;
} else {
return method.invoke(connection, params);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
2.3.1.3 ResultSetLogger 创建
当通过statement获取resultSet的时候,通过代理模式创建对应的代理类
- ResultSetLogger.newInstance(rs, statementLog, queryStack)



