- 主要代码如下所示:
package com.aoke.oa.search.plugins;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.core.toolkit.SystemClock;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlFormatter;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
@Slf4j
@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)
})
@ConditionalOnProperty(value = "oa.search.log.sql.enabled", havingValue = "true", matchIfMissing = true)
@Component
public class SqlLogInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
long timing = 0L;
Object result = null;
try {
long start = SystemClock.now();
result = invocation.proceed();
timing = SystemClock.now() - start;
} finally {
Object target = PluginUtils.realTarget(invocation.getTarget());
MetaObject metaObject = SystemMetaObject.forObject(target);
MappedStatement ms = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
Configuration configuration = ms.getConfiguration();
List<Object> params = getRuntimeParams(configuration, boundSql);
String runTimeSql = getRuntimeSql(boundSql, params);
SqlFormatter sqlFormatter = new SqlFormatter();
String formatterSql = sqlFormatter.format(runTimeSql);
log.info("\n============== Sql Start ==============" +
"\nExecute Time:{} ms - ID:{}" +
"\nExecute SQL :{}" +
"\n============== Sql End ==============",
timing, ms.getId(), formatterSql);
}
return result;
}
private String getRuntimeSql(BoundSql boundSql, List<Object> params) {
String sql = boundSql.getSql();
for (Object object : params) {
sql = sql.replaceFirst("\\?", getParameterValue(object));
}
return sql;
}
private static List<Object> getRuntimeParams(Configuration configuration, BoundSql boundSql) {
List<Object> params =