微信公众号:潇雷
当努力到一定程度,幸运自与你不期而遇
一、前言
日志的出现,是为了实现记录操作员在本系统中的操作行为,可以有效的将用户的操作保存下来,做到有迹可循,同时,良好的日志规范,能快速有效的定位问题。
二、概述
2.1 实现思路
采用spring的基于注解的aop 实现日志功能,AOP也符合开闭原则,对代码的修改是禁止的,对代码的扩展是允许的。目前的日志版本是对操作员的信息、操作的方法、操作运行的时间,请求参数和返回参数等几个重要功能进行了记录,后续若有需求可以进行修改和补充。
- 前期准备,设计日志表,需要哪些字段。
- 自定义注解,注解中需要添加哪些属性,可以标识操作的类型
- 编写切面类,通常切面类中需要需要一个切入点,以及围绕这个切入点进行的操作,可以在切入点的前面@Before、也可以在后面@After ,不过本项目中采用了在中间的形式@Around,可以记录下用户的操作时间,环绕通知可以完成前置、后置、最终等所有功能。
- 入库:编写完通知后,最后在插入日志信息。
2.2 aop的执行流程
三、数据库设计
操作日志表:
| 字段 | 类型 | 描述 |
|---|---|---|
| Oper_id | bigint | 主键id |
| Oper_model | Varchar(64) | 操作模块 |
| Oper_desc | Varchar(64) | 操作描述 |
| Oper_requ_param | Varchar(1024) | 请求参数 |
| Oper_resp_param | Varchar(1024) | 返回参数 |
| Oper_user_id | Integer | 操作员id |
| Oper_user_name | Varchar(255) | 操作员名称 |
| Oper_uri | Varchar(255) | 请求uri |
| Oper_ip | Varchar(64) | 请求ip |
| Oper_create_time | datetime | 操作时间 |
| Oper_finish_time | bigint | 请求耗时时间:毫秒 |
四、代码实现
4.1 自定义注解
@Target(ElementType.METHOD) //注解放置的目标位置,METHOD是可注解在方法级别上
@Retention(RetentionPolicy.RUNTIME) //注解在哪个阶段执行,可以通过反射获取注解信息
@Documented
public @interface OperationLog {
String operModul() default ""; // 操作模块
String operDesc() default ""; // 操作说明
}
4.2 切面类
@Aspect //声明这是一个切面类
@Component //此类交由Spring容器管理
public class OperLogAspect {
@Autowired
private OperLogService operLogService;
//设置操作日志切入点,记录操作日志, 在注解的位置切入代码
@Pointcut("@annotation(com.giant.cloud.component.aop.OperationLog)")
public void operLogPointCut(){
}
@Around(value = "operLogPointCut()")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Exception {
// 1.方法执行前的处理,相当于前置通知
// 获取方法签名
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
// 获取方法
Method method = methodSignature.getMethod();
// 从切面织入点处通过反射机制获取织入点处的方法
Map<String,Object> joinPointInfo=getJoinPointInfoMap(joinPoint);
//获取RequestAttributes
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
// 从获取RequestAttributes中获取HttpServletRequest的信息
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// 创建一个日志对象(准备记录日志)
SubOperLog operLog=new SubOperLog();
Long startTime=System.currentTimeMillis();
operLog.setOperCreateTime(DateUtil.date(startTime));//操作时间
Object result = null;
//让代理方法执行
try {
result = joinPoint.proceed();
// 获取方法上面的注解
OperationLog operationLog = method.getAnnotation(OperationLog.class);
if (operationLog != null) {
String operModul = operationLog.operModul();
String operDesc = operationLog.operDesc();
operLog.setOperModel(operModul); // 操作模块
operLog.setOperDesc(operDesc); // 操作描述
}
// 请求的参数
Map<String, String> rtnMap = converMap(request.getParameterMap());
operLog.setOperRespParam(JSON.toJSONString(result)); //返回参数
operLog.setOperUri(request.getRequestURI()); //请求uri
operLog.setOperIp(getIpAddr(request)); //获取ip
//完善请求信息
Long returnTime=System.currentTimeMillis();
operLog.setOperFinishTime(returnTime-startTime); //耗时时间
if(request.getRequestURI().equalsIgnoreCase("/login")){
if(StrUtil.isNotEmpty(joinPointInfo.get("paramMap").toString())){
operLog.setOperRequParam(joinPointInfo.get("paramMap").toString());//请求参数
String operRequParam = operLog.getOperRequParam();
String resp=operLog.getOperRespParam();
if(StrUtil.isNotEmpty(resp)){
ObjectMapper objectMapper = new ObjectMapper();
ResponseData responseData=objectMapper.readValue(resp,ResponseData.class);
SubUserVO subUserVO=objectMapper.convertValue(responseData.getData(),SubUserVO.class);
operLog.setOperUserName(subUserVO.getName());
operLog.setSysId(subUserVO.getSysId());
operLog.setOperUserId(subUserVO.getId());
operLogService.insertLog(operLog);
}
}
}else{
if(StrUtil.isNotEmpty(joinPointInfo.get("paramMap").toString())){
operLog.setOperRequParam(joinPointInfo.get("paramMap").toString());//请求参数
String operRequParam = operLog.getOperRequParam();
if(StrUtil.isNotEmpty(operRequParam)){
ObjectMapper objectMapper = new ObjectMapper();
RequestData requestData = objectMapper.readValue(operRequParam, RequestData.class);
SubUserVO user = objectMapper.convertValue(requestData.getUser(), SubUserVO.class);
operLog.setOperUserId(user.getId());
operLog.setSysId(user.getSysId());
operLog.setOperUserName(user.getName());
operLogService.insertLog(operLog);
}
}
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return result;
}
/**
* 转换request 请求参数
*
* @param paramMap request获取的参数数组
*/
private Map<String, String> converMap(Map<String, String[]> paramMap) {
Map<String, String> rtnMap = new HashMap<String, String>();
for (String key : paramMap.keySet()) {
rtnMap.put(key, paramMap.get(key)[0]);
}
return rtnMap;
}
/**
* 获取IP地址的方法
* @param request 传一个request对象下来
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ipAddress = null;
try {
ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if (ipAddress.equals("127.0.0.1")) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress = inet.getHostAddress();
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
// = 15
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
} catch (Exception e) {
ipAddress="";
}
// ipAddress = this.getRequest().getRemoteAddr();
return ipAddress;
}
/**
* 获得切入点方法信息
* @Author xiao lei
* @Date 2020/12/18 11:22
* @param * @param joinPoint
* @return java.util.Map<java.lang.String,java.lang.Object>
**/
private static Map<String, Object> getJoinPointInfoMap(JoinPoint joinPoint) {
Map<String,Object> joinPointInfo=new HashMap<>();
String classPath=joinPoint.getTarget().getClass().getName();
String methodName=joinPoint.getSignature().getName();
joinPointInfo.put("classPath",classPath);
Class<?> clazz=null;
CtMethod ctMethod=null;
LocalVariableAttribute attr=null;
int length=0;
int pos = 0;
try {
clazz = Class.forName(classPath);
String clazzName=clazz.getName();
ClassPool pool=ClassPool.getDefault();
ClassClassPath classClassPath=new ClassClassPath(clazz);
pool.insertClassPath(classClassPath);
CtClass ctClass=pool.get(clazzName);
ctMethod=ctClass.getDeclaredMethod(methodName);
MethodInfo methodInfo=ctMethod.getMethodInfo();
CodeAttribute codeAttribute=methodInfo.getCodeAttribute();
attr=(LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
if(attr==null){
return joinPointInfo;
}
length=ctMethod.getParameterTypes().length;
pos= Modifier.isStatic(ctMethod.getModifiers())?0:1;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NotFoundException e) {
e.printStackTrace();
}
Map<String,Object> paramMap=new HashMap<>();
Object[] paramsArgsValues=joinPoint.getArgs();
String[] paramsArgsNames=new String[length];
for (int i=0;i<length;i++){
paramsArgsNames[i]=attr.variableName(i+pos);
String paramsArgsName=attr.variableName(i+pos);
if(paramsArgsName.equalsIgnoreCase("request")||
paramsArgsName.equalsIgnoreCase("response")||
paramsArgsName.equalsIgnoreCase("session")
){
break;
}
Object paramsArgsValue = paramsArgsValues[i];
paramMap.put(paramsArgsName,paramsArgsValue);
joinPointInfo.put("paramMap",JSON.toJSONString(paramsArgsValue));
}
return joinPointInfo;
}
}
4.3 结果
在需要展示的service层给上自定义的注解信息,最终展示的结果如下: