背景是:项目以spring cloud eureka服务体系部署的分布式项目,前后分离,前端node直接调用各个服务接口。
原理是:以注解为切入点,在handle执行开始和结束记录请求、响应、操作信息的日志采集。
难点是:分布式日志记录入库的操作,开始时考虑抽象出来,但是持久化操作依赖于服务容器,各个服务模块无法共用一个运行 容器,解决方案是每个服务都提供子方法实现日志持久化。
代码实现:
1.新建一个注解(切入点)
package com.ww.common.annotation;
import java.lang.annotation.*;
/**
* 系统日志记录
*
* @author: Ace Lee
* @create: 2019-04-11 14:59
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface WebLog {
}
2.在需要收集日志的方法上加上@WebLog的注解
3.提供一个公共的记录日志信息的父类
package com.ww.common.filter;
import com.google.common.base.Throwables;
import com.ww.common.constant.Result;
import com.ww.common.constant.UserInfo;
import com.ww.common.constant.WwCommonInfo;
import com.ww.common.json.JacksonUtil;
import com.ww.common.web.PtaqCzrzWithBLOBs;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Date;
import java.util.UUID;
/**
* 日志采集
*
* @author: Ace Lee
* @create: 2019-04-12 09:57
*/
@Aspect
@Component
@Slf4j
public abstract class BaseAspect {
protected PtaqCzrzWithBLOBs doBefore(HttpServletRequest request){
// 接收到请求,记录请求内容
PtaqCzrzWithBLOBs consumer=new PtaqCzrzWithBLOBs();
Date now = new Date();
consumer.setWW_CZSJ(now);
consumer.setWW_QQSJ(now);
// 记录下请求内容
consumer.setWW_QQDX(request.getRequestURL().toString());
consumer.setWW_QQIP(request.getRemoteAddr());
return consumer;
}
protected void doAfterReturning(Object object,PtaqCzrzWithBLOBs consumer,HttpServletRequest request,String bz){
if(null!=consumer){
try {
consumer.setWW_XYSJ(new Date());
// 处理完请求,返回内容
String response="";
if (null!=object){
Result result = (Result) object;
response = JacksonUtil.bean2Json(object);
consumer.setWW_XYBW(response);
if (result.isSuccess()){
consumer.setWW_XYJG(WwCommonInfo.IS_SUCCESS_YES);
}else {
consumer.setWW_XYJG(WwCommonInfo.IS_SUCCESS_NO);
consumer.setWW_XYMS(result.getError());
}
}
log.info("response param: {}",response);
long elapsedTime = consumer.getWW_XYSJ().getTime() - consumer.getWW_QQSJ().getTime();
log.info("elapsed time : {} ms",elapsedTime);
consumer.setWW_XYSC(BigDecimal.valueOf(elapsedTime));
log.info("========HTTP END=========");
//设置操作人
String method = request.getMethod();
switch (method){
case "POST": case "post":
consumer.setWW_QQBW(getBody(request));
consumer.setWW_CZ("新增");
break;
case "PUT": case "put":
consumer.setWW_QQBW(getBody(request));
consumer.setWW_CZ("编辑");
break;
case "DELETE": case "delete":
consumer.setWW_CZ("删除");
break;
case "GET": case "get": default:
consumer.setWW_QQBW(getUrlParams(request));
consumer.setWW_CZ("查询");
break;
}
consumer.setWW_QQFS(method);
Object oTable = request.getAttribute(WwCommonInfo.KEY_TABLE_NAME);
if (null!=oTable){
consumer.setWW_ZYDX((String) oTable);
}
Object oId = request.getAttribute(WwCommonInfo.KEY_ENTITY_ID);
if (null!=oId){
consumer.setWW_QQID((String) oId);
}
Object oUser = request.getAttribute(WwCommonInfo.KEY_USER_INFO);
if (null!=oUser){
UserInfo userInfo = (UserInfo) oUser;
consumer.setWW_CZR(userInfo.getId());
consumer.setWW_CZRDW(userInfo.getUnitId());
}
consumer.setWW_CJSJ(new Date());
consumer.setWW_BZ(bz);
consumer.setWW_XH(String.valueOf(UUID.randomUUID()));
log.info(">>>>>>log info :{}",JacksonUtil.bean2Json(consumer));
saveConsumerLog(consumer);
} catch (Exception e) {
log.error(">>>>>>set log info error: {}", Throwables.getStackTraceAsString(e));
}
}
}
/**
* 保存操作日志
*
* @param consumer
*/
protected abstract void saveConsumerLog(PtaqCzrzWithBLOBs consumer);
/**
* 获取请求体
*
* @param request
* @return body
*/
private String getBody(HttpServletRequest request) {
String body="";
Object attribute = request.getAttribute(WwCommonInfo.KEY_BODY_INFO);
if (null!=attribute){
body = (String) attribute;
}
return body;
}
/**
* 获取请求url参数
*
* @param request
* @return body
*/
private String getUrlParams(HttpServletRequest request) {
String body="";
String attribute = request.getQueryString();
if (!StringUtils.isEmpty(attribute)){
body = URLDecoder.decode(attribute);
}
return body;
}
}
4.在各个服务模块上提供切面类的子类
这里切入点是我们的注解类,请求前和请求后的参数传递使用的是ThreadLocal,储存参数值,保存使用抽象方法,需要在各服务模块实现入库的操作。
package com.ww.config;
import com.google.common.base.Throwables;
import com.ww.common.filter.BaseAspect;
import com.ww.common.web.PtaqCzrzWithBLOBs;
import com.ww.dao.PtaqCzrzMapper;
import lombok.extern.slf4j.Slf4j;
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.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* 实现Web层的日志切面
*
* @author liyazhou
* @version v.0.1
*/
@Aspect
@Component
@Order(1)
@Slf4j
public class WebLogAspect extends BaseAspect {
@Autowired
private PtaqCzrzMapper ptaqCzrzMapper;
ThreadLocal<PtaqCzrzWithBLOBs> consumerThreadLocal = new ThreadLocal<>();
/**
* 定义一个切入点.
*
*/
@Pointcut("@annotation(com.ww.common.annotation.WebLog)")
public void webLog(){}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint){
log.info("========HTTP START=========");
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
consumerThreadLocal.set(doBefore(request));
}
@AfterReturning(value = "webLog()",returning = "object")
public void doAfterReturning(Object object){
PtaqCzrzWithBLOBs consumer = consumerThreadLocal.get();
consumerThreadLocal.remove();
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
doAfterReturning(object,consumer,request,"OPEN");
}
/**
* 保存操作日志
*
* @param consumer
*/
@Override
protected void saveConsumerLog(PtaqCzrzWithBLOBs consumer) {
try {
ptaqCzrzMapper.insertSelective(consumer);
log.info(">>>>>>insert log info success");
} catch (Exception e) {
log.error(">>>>>>insert log info error: {}",Throwables.getStackTraceAsString(e));
}
}
}