1.创建系统日志数据库表

2.maven坐标
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.7</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
3.创建系统日志实体类
@Data
public class SysLog implements Serializable {
private String id;
private int logType;
private String logContent;
private int operateType;
private String userid;
private String username;
private String ip;
private String method;
private String requestUrl;
private String requestParam;
private String requestType;
private long costTime;
private String createBy;
private Date createTime;
private String updateBy;
private Date updateTime;
}
4.创建系统日志注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AutoLog {
String value() default "";
int logType() default 2;
int operateType() default 0;
}
5.创建日志注解切面类
@Aspect
@Component
public class AutoLogAspect {
@Autowired
SysLogService sysLogService;
private static Logger logger = LoggerFactory.getLogger(AutoLogAspect.class);
@Pointcut("@annotation(com.example.demo.commit.annotation.AutoLog)")
public void logPointCut(){}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
System.out.println("日志");
Object result = point.proceed();
long time = System.currentTimeMillis()-beginTime;
saveSysLog(point,time,result);
return result;
}
private void saveSysLog(ProceedingJoinPoint point,long time,Object obj){
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
SysLog dto = new SysLog();
AutoLog syslog = method.getAnnotation(AutoLog.class);
if (syslog != null){
String content = syslog.value();
dto.setLogType(syslog.logType());
dto.setLogContent(content);
}
String className = point.getTarget().getClass().getName();
String methodName = signature.getName();
dto.setMethod(className+"."+methodName+"()");
if (dto.getLogType() == 2){
dto.setOperateType(getOperateType(methodName,syslog.operateType()));
}
HttpServletRequest request = getHttpServletRequest();
dto.setRequestParam(getRequestParams(request,point));
dto.setIp(getIpAddr(request));
TUser user = (TUser) SecurityUtils.getSubject().getPrincipal();
if (user != null){
dto.setUserid(user.getUserName());
dto.setUsername(user.getPassWord());
}
dto.setCostTime(time);
dto.setCreateTime(new Date());
sysLogService.save(dto);
}
private int getOperateType(String methodName , int operateType){
if (operateType>0){
return operateType;
}
if (methodName.startsWith("list")){
return 1;
}
if (methodName.startsWith("add")){
return 2;
}
if (methodName.startsWith("edit")){
return 3;
}
if (methodName.startsWith("delete")){
return 4;
}
if (methodName.startsWith("import")){
return 5;
}
if (methodName.startsWith("export")){
return 6;
}
return 1;
}
private HttpServletRequest getHttpServletRequest(){
return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
}
private String getRequestParams(HttpServletRequest request, JoinPoint joinPoint){
String httpMethod = request.getMethod();
String param = "";
if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) || "PATCH".equals(httpMethod)){
Object[] paramArray = joinPoint.getArgs();
Object[] arguments = new Object[paramArray.length];
for (int i = 0; i < paramArray.length; i++) {
if (paramArray[i] instanceof BindingResult || paramArray[i] instanceof ServletRequest || paramArray[i] instanceof ServletResponse || paramArray[i] instanceof MultipartFile){
continue;
}
arguments[i] = paramArray[i];
}
PropertyFilter propertyFilter = new PropertyFilter() {
@Override
public boolean apply(Object object, String name, Object value) {
if (value!=null && value.toString().length()>500){
return false;
}
return true;
}
};
param = JSONObject.toJSONString(arguments,propertyFilter);
}else {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Object[] args = joinPoint.getArgs();
LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
String[] parameterNames = u.getParameterNames(method);
if (args != null && parameterNames !=null){
for (int i = 0; i < args.length; i++) {
param += " " + parameterNames[i] +": " + args[i];
}
}
}
return param;
}
public String getIpAddr(HttpServletRequest request){
String ip = null;
try {
ip = request.getHeader("x-forwarded-for");
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("HTTP_CLIENT-IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("HTTP_X-FORWARDED-FOR");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)){
ip = request.getRemoteAddr();
}
}catch (Exception e){
logger.error("IP error",e);
}
return ip;
}
}
6.在controller层的方法添加系统日志注解
@AutoLog(value = "easyPoi导入")
@ApiOperation("easyPoi导入")
@GetMapping("/importEasyPoi")
@ResponseBody
public Result<TUser> easyPoiImport(@RequestParam("file")MultipartFile file) {
try {
userService.easyPoiImport(file);
return ResultUtil.success();
}catch(Exception e){
e.printStackTrace();
return ResultUtil.fail(201,"导入失败");
}
}
gitee地址