package com.mypro.api.config; import com.alibaba.fastjson.JSON; import com.mypro.api.entity.Apilogs; import com.mypro.api.mapper.ApilogsMapper; import com.mypro.api.model.TokenInfo; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.time.LocalDateTime; @Component @Aspect public class LogsAspect { @Resource private ApilogsMapper apilogsMapper; @Before("execution(* com.mypro.api.controller.*.*(..))") public void logBefore(JoinPoint joinPoint) throws Exception { String methodName = joinPoint.getSignature().getName(); if(methodName.equals("UploadWithStream")){ saveLog("before", methodName, null); }else { Object[] args = joinPoint.getArgs(); String argsJson = JSON.toJSONString(args); saveLog("before", methodName, argsJson); } } @AfterReturning(returning = "result", pointcut = "execution(* com.mypro.api.controller.*.*(..))") public void logAfterReturning(JoinPoint joinPoint, Object result) throws Exception { String methodName = joinPoint.getSignature().getName(); if(methodName.equals("list")) { saveLog("after", methodName, null); }else{ String argsJson = JSON.toJSONString(result); saveLog("after", methodName, argsJson); } } private void saveLog(String type,String methodName,String argsJson) throws Exception { // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); String uri=request.getRequestURI(); String ipstr = getClientIpAddress(request); Apilogs log=new Apilogs(); log.setType(type); log.setMethodName(methodName); log.setArgs(argsJson); log.setIp(ipstr); log.setUri(uri); log.setCreateTime(LocalDateTime.now()); TokenInfo info=getAuthTokenInfo(request); if(info!=null){ log.setUserName(info.getUserName()); log.setUserId(info.getUserId()); } apilogsMapper.insert(log); } /** * 获取登录信息 * @param request * @return * @throws Exception */ private TokenInfo getAuthTokenInfo(HttpServletRequest request) throws Exception { //从拦截器中获取tokeninfo Object obj=request.getAttribute("tokeninfo"); if(obj!=null){ return (TokenInfo)obj; }else{ return null; } } /** * 获取客户端ip包括nginx反向代理后的 * @param request * @return */ private String getClientIpAddress(HttpServletRequest request) { String xForwardedForHeader = request.getHeader("X-Forwarded-For"); if (xForwardedForHeader != null) { String[] ips = xForwardedForHeader.split(","); if (ips.length > 0) { return ips[0].trim(); } } return request.getRemoteAddr(); } }