springboot 打印sql执行信息日志并输入指定文件中 (sql语句,执行时间)
package com.insigma.oa.common.mybatisplus;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.apache.ibatis.session.SqlSessionFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;
import java.io.*;
import java.util.Arrays;
/**
* @author xc
* * @date 2021/04/25
*/
@ConditionalOnExpression("${oa.sqlEnabled}==1") //滿足才当做bean加载到容器中
@Aspect
@Component
@Log4j2
public class MapperAspect {
@Value("${oa.slowLogTime}")
private Integer slowLogTime;
@Value("${oa.sql-path}")
private String path;
@Autowired
private SqlSessionFactory sqlSessionFactory;
@AfterReturning("execution(* com.insigma.oa.*.*.*Mapper.*(..))")
public void logServiceAccess(JoinPoint joinPoint) {
log.info("Completed: " + joinPoint);
}
/**
* 监控com.lsj.xcjfs.dao..*Mapper包及其子包的所有public方法
*/
@Pointcut("execution(* com.insigma.oa.*.*.*Mapper.*(..))")
private void pointCutMethod() {
}
/**
* 声明环绕通知
*
* @param pjp
* @return
* @throws Throwable
*/
@Around("pointCutMethod()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
long begin = System.nanoTime();
Object obj = pjp.proceed();
long end = System.nanoTime();
// log.info("调用Mapper方法:{},参数:{},执行耗时:{}纳秒,耗时:{}毫秒",
// pjp.getSignature().toString(), Arrays.toString(pjp.getArgs()),
// (end - begin), (end - begin) / 1000000);
if((end - begin) / 1000000>slowLogTime) {
String sql = SqlUtils.getMybatisSql(pjp, sqlSessionFactory);
StringBuffer st = new StringBuffer();
st.append("调用Mapper方法:").append(pjp.getSignature().toString()).append("\n").
append("执行的sql语句:").append(sql).append("\n").
// append("参数:") .append(Arrays.toString(pjp.getArgs())).
append("耗时:").append((end - begin) / 1000000).append("毫秒").append("\n\n\n");
WriteNewLog(st.toString(), path);
}
return obj;
}
public static void WriteNewLog(String jsonlog, String logpath){
FileWriter fw = null;
try {
//如果文件存在,则追加内容;如果文件不存在,则创建文件
File f=new File(logpath);
if(!f.isFile()){
f.createNewFile();
}
fw = new FileWriter(f, true);
} catch (IOException e) {
e.printStackTrace();
}
PrintWriter pw = new PrintWriter(fw);
pw.println(jsonlog);
pw.flush();
try {
fw.flush();
pw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void method1() {
FileWriter fw = null;
try {
//如果文件存在,则追加内容;如果文件不存在,则创建文件
File f=new File("E:\\dd.txt");
fw = new FileWriter(f, true);
} catch (IOException e) {
e.printStackTrace();
}
PrintWriter pw = new PrintWriter(fw);
pw.println("追加内容");
pw.flush();
try {
fw.flush();
pw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.insigma.oa.common.mybatisplus;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.text.DateFormat;
import java.util.*;
/**
* @author xc
* * @date 2021/04/25
*/
public class SqlUtils {
/**
* 获取aop中的SQL语句
* @param pjp
* @param sqlSessionFactory
* @return
* @throws IllegalAccessException
*/
public static String getMybatisSql(ProceedingJoinPoint pjp, SqlSessionFactory sqlSessionFactory) throws IllegalAccessException {
try {
Map<String, Object> map = new HashMap<>();
//1.获取namespace+methdoName
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
String namespace = method.getDeclaringClass().getName();
String methodName = method.getName();
//2.根据namespace+methdoName获取相对应的MappedStatement
Configuration configuration = sqlSessionFactory.getConfiguration();
MappedStatement mappedStatement = configuration.getMappedStatement(namespace + "." + methodName);
// //3.获取方法参数列表名
// Parameter[] parameters = method.getParameters();
//4.形参和实参的映射
Object[] objects = pjp.getArgs(); //获取实参
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (int i = 0; i < parameterAnnotations.length; i++) {
Object object = objects[i];
if (parameterAnnotations[i].length == 0) { //说明该参数没有注解,此时该参数可能是实体类,也可能是Map,也可能只是单参数
if (object.getClass().getClassLoader() == null && object instanceof Map) {
map.putAll((Map<? extends String, ?>) object);
System.out.println("该对象为Map");
} else {//形参为自定义实体类
map.putAll(objectToMap(object));
System.out.println("该对象为用户自定义的对象");
}
} else {//说明该参数有注解,且必须为@Param
for (Annotation annotation : parameterAnnotations[i]) {
if (annotation instanceof Param) {
map.put(((Param) annotation).value(), object);
}
}
}
}
//5.获取boundSql
BoundSql boundSql = mappedStatement.getBoundSql(map);
return showSql(configuration, boundSql);
}catch (Exception e){
return null;
}
}
/**
* 解析BoundSql,生成不含占位符的SQL语句
* @param configuration
* @param boundSql
* @return
*/
private static String showSql(Configuration configuration, BoundSql boundSql) {
Object parameterObject = boundSql.getParameterObject();
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
if (parameterMappings.size() > 0 && parameterObject != null) {
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));
} else {
MetaObject metaObject = configuration.newMetaObject(parameterObject);
for (ParameterMapping parameterMapping : parameterMappings) {
String propertyName = parameterMapping.getProperty();
String[] s = metaObject.getObjectWrapper().getGetterNames();
s.toString();
if (metaObject.hasGetter(propertyName)) {
Object obj = metaObject.getValue(propertyName);
sql = sql.replaceFirst("\\?", getParameterValue(obj));
} else if (boundSql.hasAdditionalParameter(propertyName)) {
Object obj = boundSql.getAdditionalParameter(propertyName);
sql = sql.replaceFirst("\\?", getParameterValue(obj));
}
}
}
}
return sql;
}
/**
* 若为字符串或者日期类型,则在参数两边添加''
* @param obj
* @return
*/
private static String getParameterValue(Object obj) {
String value = null;
if (obj instanceof String) {
value = "'" + obj.toString() + "'";
} else if (obj instanceof Date) {
DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
value = "'" + formatter.format(new Date()) + "'";
} else {
if (obj != null) {
value = obj.toString();
} else {
value = "";
}
}
return value;
}
/**
* 获取利用反射获取类里面的值和名称
*
* @param obj
* @return
* @throws IllegalAccessException
*/
private static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>();
Class<?> clazz = obj.getClass();
System.out.println(clazz);
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = field.get(obj);
map.put(fieldName, value);
}
return map;
}
}
配置文件中
oa:
sqlEnabled: 1 #是否开启sql慢查询 1开启
slowLogTime: 200 #毫秒 超过多少打印
sql-path: D:\log.txt #慢sql存放的地方