Java 开发中常用的几款日志框架有很多种,并且这些日志框架来源于不同的开源组织,给用户暴露的接口也有很多不同之处,所以很多开源框架会自己定义一套统一的日志接口,兼容上述第三方日志框架,供上层使用。
一般实现的方式是使用 适配器模式,将各个第三方日志框架接口转换为框架内部自定义的日志接口。MyBatis 也提供了类似的实现,这里我们就来简单了解一下。

适配器模式是什么?
简单来说,适配器模式主要解决的是由于接口不能兼容而导致类无法使用的问题,这在处理遗留代码以及集成第三方框架的时候用得比较多。其核心原理是:通过组合的方式,将需要适配的类转换成使用者能够使用的接口。

打印SQL语句

这里演示Mybatis在运行时怎么输出SQL语句,具体分析见原理章节。

单独使用Mybatis

在mybatis.xml配置文件中添加如下配置:

<setting name="logImpl" value="STDOUT_LOGGING" />

和SpringBoot整合

有两种方式,第一种也是利用StdOutImpl实现类去实现打印,在application.yml配置文件填写如下:

#mybatis配置
mybatis:
  # 控制台打印sql日志
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

其次我们还可以通过指定日志级别来输出SQL语句:

SpringBoot默认使用的SL4J(日志门面)+Logback(具体实现)的日志组合

logging:
  level:
    xx包名: debug

日志模块

MyBatis 自定义的 Log 接口位于 org.apache.ibatis.logging 包中,相关的适配器也位于该包中。
首先是 LogFactory 工厂类,它负责创建 Log 对象,在 LogFactory 类中有一段静态代码块,其中会依次加载各个第三方日志框架的适配器,同时也支持使用useCustomLogging来自定义适配器。

static {
    tryImplementation(LogFactory::useSlf4jLogging);
    tryImplementation(LogFactory::useCommonsLogging);
    tryImplementation(LogFactory::useLog4J2Logging);
    tryImplementation(LogFactory::useLog4JLogging);
    tryImplementation(LogFactory::useJdkLogging);
    tryImplementation(LogFactory::useNoLogging);
}

/**
 * 用于支持自定义日志适配器
 */
public static synchronized void useCustomLogging(Class<? extends Log> clazz) {
    setImplementation(clazz);
}

以 JDK Logging 的加载流程(useJdkLogging() 方法)为例,其具体代码实现和注释如下:

/**
 * 首先会检测 logConstructor 字段是否为空,
 * 1.如果不为空,则表示已经成功确定当前使用的日志框架,直接返回;
 * 2.如果为空,则在当前线程中执行传入的 Runnable.run() 方法,尝试确定当前使用的日志框架
 */
private static void tryImplementation(Runnable runnable) {
    if (logConstructor == null) {
        try {
            runnable.run();
        } catch (Throwable t) {
            // ignore
        }
    }
}

public static synchronized void useJdkLogging() {
    setImplementation(org.apache.ibatis.logging.jdk14.Jdk14LoggingImpl.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());
        // 加载成功,则更新logConstructor字段,记录适配器的构造方法
        logConstructor = candidate;
    } catch (Throwable t) {
        throw new LogException("Error setting Log implementation.  Cause: " + t, t);
    }
}

简单分析原理

这里我们直接看到org.apache.ibatis.executor.BaseExecutor#getConnection方法,了解Mybatis的应该都知道Mybatis在执行sql操作的时候会去获取数据库连接

protected Connection getConnection(Log statementLog) throws SQLException {
    Connection connection = transaction.getConnection();
    // 判断日志级别是否为Debug,是的话返回代理对象
    if (statementLog.isDebugEnabled()) {
        return ConnectionLogger.newInstance(connection, statementLog, queryStack);
    } else {
        return connection;
    }
}

可以看到我注释的那行,它通过判断日志级别来判断是否返回ConnectionLogger代理对象,那么我们前面提到 Log 接口的实现类中StdOutImpl它的isDebugEnabled其实是永远返回 true,代码如下:

并且它直接用的 System.println去输出的SQL信息

public class StdOutImpl implements Log {

  // ...省略无关代码

  @Override
  public boolean isDebugEnabled() {
    return true;
  }

  @Override
  public void error(String s) {
    System.err.println(s);
  }
  // ...省略无关代码
}

ConnectionLogger 代理对象

而代理对象是通过JDK动态代理实现的,必然需要实现InvocationHandler接口

// org.apache.ibatis.logging.jdbc.ConnectionLogger#newInstance
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);
}

@Override
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;
        } else if ("prepareCall".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;
        } 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);
    }
}

可以看到代码中调用的debug等日志输出方法,它们其实来自于org.apache.ibatis.logging.jdbc.BaseJdbcLogger#debug,因为ConnectionLogger继承了BaseJdbcLogger,而debug方法中则是调用的statementLog

  protected void debug(String text, boolean input) {
    if (statementLog.isDebugEnabled()) {
      statementLog.debug(prefix(input) + text);
    }
  }

到这里起码你知道了为什么我们通过配置 MyBatis 所用日志的具体实现 logImpl就可以实现日志输出到控制台的效果了。

statementLog 是在什么时候变成 StdOutImpl的?

如果写过Mybatis配置文件的话,应该都知道中有一个属性logImpl,它的作用如下:
image.png
官方链接:https://mybatis.org/mybatis-3/zh/configuration.html#settings
Mybatis启动时会解析Mybatis配置文件,这个时候会去读取我们配置的logImpl属性保存到configuration对象中,然后如果配置了logImpl的话就通过LogFactory.useCustomLogging方法先指定好日志适配器的构造方法,这里不懂的看第一节日志模块。

// org.apache.ibatis.builder.xml.XMLConfigBuilder#loadCustomLogImpl  
private void loadCustomLogImpl(Properties props) {
    Class<? extends Log> logImpl = resolveClass(props.getProperty("logImpl"));
    configuration.setLogImpl(logImpl);
}

public void setLogImpl(Class<? extends Log> logImpl) {
    // 如果你配置了 logImpl 属性
    if (logImpl != null) {
        this.logImpl = logImpl;
        LogFactory.useCustomLogging(this.logImpl);
    }
}

然后在构建MappedStatement的时候就已经将日志对象初始化好了

每个MappedStatement对应了我们自定义Mapper接口中的一个方法,它保存了开发人员编写的SQL语句、参数结构、返回值结构、Mybatis对它的处理方式的配置等细节要素,是对一个SQL命令是什么、执行方式的完整定义。

public Builder(Configuration configuration, String id, SqlSource sqlSource, SqlCommandType sqlCommandType) {
    // ...省略无关代码
    mappedStatement.statementLog = LogFactory.getLog(logId);
    // ...省略无关代码
}

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);
    }
}

这里调用的getLog方法里用到的logConstructor在上述LogFactory.useCustomLogging中已经赋了值,此处参考上面描述的日志模块加载流程~
最后SpringBoot的就不概述了

  • 第一种方式其实也是同理
  • 第二种方式是通过修改了日志级别,然后使 isDebugEnabled 返回true,去返回代理对象,然后去输出SQL语句。

感兴趣的还可以看看SQL语句的输出是怎么输出的,具体在ConnectionLogger的invoke方法中,你会发现熟悉的Preparing: "和"Parameters: "

完结撒花,看完了点个赞呗~🥳。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐