org.apache.logging.log4j
log4j-api
${log4j2.version}
org.apache.logging.log4j
log4j-core
${log4j2.version}
org.apache.logging.log4j
log4j-web
${log4j2.version}
注:本人使用的是2.7版本的log4j2
log4j2在启动的时候会默认加载名为log4j2.xml的配置文件
D:/log4j2/mybatis/genertor/logs/
error
org.apache.logging.log4j.web.Log4jServletContextListener
log4jServletFilter
org.apache.logging.log4j.web.Log4jServletFilter
log4jServletFilter
/*
REQUEST
FORWARD
INCLUDE
ERROR
注:加上上述配置后,就能在项目启动是加载log4j2
注:settings配置完毕后,即可实现SQL语句的打印!控制台打印如下结果:
2017-10-23 16:38:01,021 DEBUG (BaseJdbcLogger.java:145) - ==> Preparing: SELECT count(*) FROM t_user
2017-10-23 16:38:01,056 DEBUG (BaseJdbcLogger.java:145) - ==> Parameters:
2017-10-23 16:38:01,084 DEBUG (BaseJdbcLogger.java:145) - <== Total: 1
package com.stu.interceptor;
import java.sql.Statement;
import java.util.Properties;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
/**
* Sql执行时间记录拦截器
*/
@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
@Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
@Signature(type = StatementHandler.class, method = "batch", args = { Statement.class })})
public class SqlCostInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
long startTime = System.currentTimeMillis();
try {
return invocation.proceed();
} finally {
long endTime = System.currentTimeMillis();
long sqlCost = endTime - startTime;
System.out.println("执行耗时 : [" + sqlCost + "ms ] ");
}
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
注:Interceptor接口是Mybatis官方提供的拦截接口,创建一个类实现该接口并重写其三个方法并将该类配置在Mybatis的配置文件中,即可拦截SQL语句的执行过程
2017-10-23 16:38:01,091 DEBUG (BaseJdbcLogger.java:145) - ==> Preparing: select id, username, password, state, isdel, add_time, money, left_money from t_user limit ?,?
2017-10-23 16:38:01,093 DEBUG (BaseJdbcLogger.java:145) - ==> Parameters: 0(Integer), 15(Integer)
2017-10-23 16:38:01,128 DEBUG (BaseJdbcLogger.java:145) - <== Total: 15
执行耗时 : [36ms ]
写在最后:如需转载,请注明出处,如果有什么问题,欢迎在评论区询问