Java日志有很多,log4j,log4j2,comons-logging等,mybatis为不同日志提供了适配,how?
1、定义接口Log,日志框架需对应的实现,如log4j的实现类Log4jImpl
2、定义LogFactory作为获取日志的入口
LogFactory静态代码块会初始化一个可用的Log实现类:
还有一个静态方法userCustomLogging
public static synchronized void useCustomLogging(Class<? extends Log> clazz) { setImplementation(clazz); }
来使用自定义的日志框架,how?
Class<? extends Log> logImpl = (Class<? extends Log>)resolveClass(props.getProperty("logImpl")); configuration.setLogImpl(logImpl);
就是在setting中定义的:<setting name="logImpl" value="log4j" />
其实上面的setting也可以不配置的,注意LogFactory的静态代码块,先去使用了SL4J,Log4j可以作为其实现的,
要使用Log4j,配置文件来一发:
#配置根Logger 后面是若干个Appender
log4j.rootLogger=DEBUG,stdout
# ConsoleAppender 输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%c]-[%p] %m%n
当然pom中的依赖(sl4j, sl4j-log4j,log4j)是需要的,OK,debug,sql语句,参数,缓存命中率都有了
啥,sql日志就有了?你并没做这个功能,无需怀疑,肯定是框架做的,看看mybatis如何打印sql?代理Connection,PrepareStatement,下面截图看从头到尾的流程:
1、构建MappedStatement时生产log对象:
2、getConnection,返回Connection的代理:
3、如果调用的是prepareStatement,Connection代理的InvocationHandler打印日志,并生成PrepareStatement代理类,
PrepareStatementLogger、ResultSetLogger和ConnectionLogger相似:
MappedStatement的statementLog构建传入了id(id就是namespace,如
com.hhg.jerry.dao.CityDao)顺带提下log4j的功能,若不想输出(CityMapper.xml)相关的sql这样配置下就ok了:
mybatis的日志就这么多