日志加入数据库可以依靠springAop实现
首先pom文件导入
<!--spring切面aop依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
写我们的配置类
package com.example.fuwu.zhuJie;
import org.apache.http.HttpRequest;
import java.lang.annotation.*;
/**
* 自定义注解类
*/
@Target(ElementType.METHOD) //注解放置的目标位置,METHOD是可注解在方法级别上
@Retention(RetentionPolicy.RUNTIME) //注解在哪个阶段执行
@Documented //生成文档
public @interface MyLog {
String value() default "";
}
加上切面类
package com.example.fuwu.riZhi;
import com.example.fuwu.mybatis.entity.SysLog;
import com.example.fuwu.service.riZhi;
import com.example.fuwu.zhuJie.MyLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
/**
* 系统日志:切面处理类
*/
@Aspect
@Component
public class SysLogAspect {
@Autowired
private riZhi riZhi;
//定义切点 @Pointcut
//在注解的位置切入代码
@Pointcut("@annotation( com.example.fuwu.zhuJie.MyLog)")
public void logPoinCut() {
}
private Logger logger = LoggerFactory.getLogger(getClass());
//切面 配置通知
@AfterReturning("logPoinCut()")
public void saveSysLog(JoinPoint joinPoint) {
System.out.println("切面。。。。。");
//保存日志
SysLog sysLog = new SysLog();
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//
//从切面织入点处通过反射机制获取织入点处的方法
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//获取切入点所在的方法
Method method = signature.getMethod();
//获取操作
MyLog myLog = method.getAnnotation(MyLog.class);
if (myLog != null) {
String value = myLog.value();
sysLog.setMethod(value);//保存获取的操作
}
//获取请求的类名
String className = joinPoint.getTarget().getClass().getName();
//获取请求的方法名
String methodName = method.getName();
sysLog.setMethod(className + "." + methodName);
//请求的参数
Object[] args = joinPoint.getArgs();
// 加入ip
sysLog.setIp(request.getRemoteAddr());
sysLog.setCreateDate(new Date());
System.out.println(sysLog);
//调用service保存SysLog实体类到数据库
riZhi.insertrizhi(sysLog);
}
}
启动类加上我们配置的注解