SpringCloud使⽤AOP记录⽤户操作⽇志
使⽤springcloud 和springboot没有多⼤区别,主要是关于aop的代码要放在公共项⽬common中,⼀开始我放在某个业务⼯程t1中,其
他没有依赖t1的⼯程,都不能使⽤该log。
该⽇志的功能: 记录⽤户每⼀次的⾏为的⽤户ID,使⽤时间,请求参数,返回结果,模块,请求时长。【将该⽇志数据存到数据库中,能
够让cloud项⽬所有的controller接⼝都能使⽤,不⽤⾃定义注解】
使⽤了环绕通知
=====================================================
代码:
1.⽇志实体类:
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class SysLog implements Serializable {
private Integer id;
private String username;
private String operation;
private String time;
private String method;
private String params;
private String ip;
/
/  @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private String createTime;
private String result;
}
2.获取⽤户IP地址:
public class IPUtils {
/**
* 获取IP地址
*
* 使⽤Nginx等反向代理软件,则不能通过RemoteAddr()获取IP地址
* 如果使⽤了多级反向代理的话,X-Forwarded-For的值并不⽌⼀个,⽽是⼀串IP地址,X-Forwarded-For中第⼀个⾮unknown的有效IP字符串,则为真实IP地址    */
public static String getIpAddr(HttpServletRequest request) {
String ip = Header("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = Header("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = Header("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = RemoteAddr();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
}
}
3.
public class HttpContextUtils {
public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) RequestAttributes()).getRequest();
}
}
4.正⽂:
@Slf4j
@Aspect
@Component
public class LogAspects {
//  @Autowired
//  private SysLogDao sysLogDao;
//    @Pointcut("@annotation(fig.log.Log)")
//    public void pointcut() { }
//    @Around("pointcut()")
@Around("execution(* com.lezhi.*.controller.*.*(..))")
public Object around(ProceedingJoinPoint point) {
Object result = null;
springboot aop
long beginTime = System.currentTimeMillis();
try {
// 执⾏⽅法
result = point.proceed();
<("返回值为:"+ JSONString(result));
} catch (Throwable e) {
e.printStackTrace();
}
// 执⾏时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
// 保存⽇志
saveLog(point, time,result);
return result;
}
private void saveLog(ProceedingJoinPoint joinPoint, long time,Object result ) {
MethodSignature signature = (MethodSignature) Signature();
Method method = Method();
SysLog sysLog = new SysLog();
Log logAnnotation = Annotation(Log.class);
//        if (logAnnotation != null) {
//            // 注解上的描述
//            sysLog.setOperation(logAnnotation.value());
/
/        }
// 请求的⽅法名
String className = Target().getClass().getName();
String methodName = Name();
sysLog.setMethod(className + "." + methodName + "()");
// 请求的⽅法参数值
Object[] args = Args();
// 请求的⽅法参数名称
LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();        String[] paramNames = u.getParameterNames(method);
if (args != null && paramNames != null) {
String params = "";
for (int i = 0; i < args.length; i++) {
params += "  " + paramNames[i] + ": " + args[i];
params += "  " + paramNames[i] + ": " + args[i];
}
sysLog.setParams(params);
}
// 获取request
HttpServletRequest request = HttpServletRequest();
// 设置IP地址
sysLog.IpAddr(request));
/
/ 模拟⼀个⽤户名
SecurityUserDetails userDetails = (SecurityUserDetails) Context().getAuthentication().getPrincipal();        Long userId = Long.Username());
sysLog.setUserId(userId);
sysLog.setTime( String.valueOf(time)+"毫秒");
//设置⽇期格式  HH:mm:ss中的HH⼤写为24⼩时制。HH和hh的差别是前者为24⼩时制,后者为12⼩时制
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// new Date()为获取当前系统时间
String dateTime=df.format(new Date());
sysLog.setCreateTime(dateTime);
sysLog.setResult( JSONString(result));
<("新增的log⽇志::"+String());
// 保存系统⽇志
//    sysLogDao.saveSysLog(sysLog);
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。