@Intercepts({
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
}) public class SimpleLogPlugin implements Interceptor {

@Override
public Object intercept(Invocation invocation) throws Throwable {
long startTime = System.currentTimeMillis();
try {
return invocation.proceed();
} finally {
long endTime = System.currentTimeMillis();
System.out.println("SQL执行耗时:" + (endTime - startTime) + "ms");
}
}
}

@Intercepts({
@Signature(type = Executor.class, method = "query",
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
}) public class PerformanceMonitorPlugin implements Interceptor {
private static final Logger logger = LoggerFactory.getLogger(PerformanceMonitorPlugin.class);
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
Object parameter = invocation.getArgs()[1];
long startTime = System.currentTimeMillis();
try {
Object result = invocation.proceed();
long endTime = System.currentTimeMillis();
// 记录完整的性能数据
logPerformanceData(mappedStatement, parameter, endTime - startTime, result);
return result;
} catch (Exception e) {
long endTime = System.currentTimeMillis();
logger.error("SQL执行失败,耗时:{}ms", endTime - startTime);
throw e;
}
}
private void logPerformanceData(MappedStatement mappedStatement, Object parameter,
long costTime, Object result) {
if (costTime > 1000) { // 超过1秒的查询记录警告
logger.warn("慢SQL检测 - 执行时间:{}ms, SQL: {}", costTime,
mappedStatement.getBoundSql(parameter).getSql());
}
// 记录常规性能数据
logger.info("SQL执行统计 - 时间:{}ms, 方法:{}",
costTime, mappedStatement.getId());
}
}