SpringBoot结合Aop记录请求日志

Aop指面向切面编程,在spring mvc 里已经出现,springBoot作为体系之一,也包含AOP。在一个Web应用中,我希望记录所有请求的远端地址,请求客户端类型,请求URI等记录,一方面是为了做安全记录,同时也可以提供后期考虑数据分析的基础数据,具体可以通过Headers信息获取。常见的比较重要的头信息包括 user-agent, accept等,其他如URI,queryString 等在serveletRequest中得到。如果单独考虑每个方法里附加方法,太过笨拙,AOP的特性提供了很好的方案。可以按照包,类,方法,注解各个级别作为切点,拦截访问请求,做附加处理。当然,现实中各种项目也是通过AOP实现类似的功能,包括访问日志记录,验证头信息,数据库SQL分析统计,redis请求统计等。


看个图放松

基本功能已经完成,中间有遇到AOP不生效的情况,查找相关资料,有建议添加配置项spring.aop.auto=true , spring.aop.proxy-target-class=true,后者是使用CGLIB代理,可能有性能下降。其实都不需要这些配置,默认是生效的,后面解释原因;还有建议添加@EnableProxyTargetClass,原因也类似;以及建议添加@ComponentScan覆盖AOP目录。以上可能是在某些情况下的适用方案。这次遇到的问题其实是切入条件不正确,在相关例子中缺少了public前缀,导致的不生效。正确是:@Pointcut("execution (public * com.igoso.me.gallery.controller.*.*(..))")
另外有个缺陷是,为查询记录,添加了查询的HTTP请求,本身也会被记录其中,后续再考虑在入库之前进行过滤,目前没有影响。

补充:多个Aop可以使用@Order(n),来控制顺序。

如下是整个Aspect的代码:

/**
 * created by igoso at 2018/5/26
 **/
@Aspect
@Component
public class HttpLogAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger("HTTP_LOG");

    @Resource
    private HeaderDetailDao headerDetailDao;

    @Pointcut("execution (public * com.igoso.me.gallery.controller.*.*(..))")
    public void log() {

    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == attributes) {
            LOGGER.error("get servlet request attributes null");
            return;
        }
        HttpServletRequest request = attributes.getRequest();

        Map headers = new HashMap<>();
        String name;
        request.getAttributeNames();
        for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
            name = e.nextElement().toString();
            headers.put(name, request.getHeader(name));
        }

        headers.put("uri", request.getRequestURI());
        headers.put("queryString", request.getQueryString());
        headers.put("remoteAddr", request.getRemoteAddr());
        headers.put("method", request.getMethod());
        headers.put("remoteHost",request.getRemoteHost());
        headers.put("remotePort",String.valueOf(request.getRemotePort()));
        headers.put("protocol",request.getProtocol());

        HeaderDetail headerDetail = new HeaderDetail(headers, JSON.toJSONString(headers));
        LOGGER.debug(JSON.toJSONString(headers,true));

        try {
            headerDetailDao.insert(headerDetail);
        } catch (Exception e) {
            LOGGER.error("insert header detail error:{}",e);
        }

    }

}


/**
 * created by igoso at 2018/5/26
 **/

@Getter
@Setter
@NoArgsConstructor
public class HeaderDetail extends Entity{

    private String acceptLanguage;
    private String method;
    private String remoteHost;
    private String remotePort;
    private String remoteAddr;
    private String queryString;
    private String uri;
    private String accept;
    private String localHost;
    private String acceptEncoding;
    private String userAgent;
    private String protocol;
    private String extensions;//json

    public HeaderDetail(Map origin, String extensions) {
        this.acceptLanguage = origin.get(HeaderAttributes.ACCEPT_LANGUAGE);
        this.method = origin.get(HeaderAttributes.METHOD);
        this.remoteAddr = origin.get(HeaderAttributes.REMOTE_ADDR);
        this.remoteHost = origin.get(HeaderAttributes.REMOTE_HOST);
        this.remotePort = origin.get(HeaderAttributes.REMOTE_PORT);
        this.queryString = origin.get(HeaderAttributes.QUERY_STRING);
        this.uri = origin.get(HeaderAttributes.URI);
        this.accept = origin.get(HeaderAttributes.ACCEPT);
        this.localHost = origin.get(HeaderAttributes.LOCAL_HOST);
        this.acceptEncoding = origin.get(HeaderAttributes.ACCEPT_ENCODING);
        this.userAgent = origin.get(HeaderAttributes.USER_AGENT);
        this.protocol = origin.get(HeaderAttributes.PROTOCOL);

        this.extensions = extensions; //other
    }

    private class HeaderAttributes{
        static final String ACCEPT_LANGUAGE = "accept-language";
        static final String METHOD = "method";
        static final String REMOTE_ADDR = "remoteAddr";
        static final String REMOTE_HOST = "remoteHost";
        static final String REMOTE_PORT = "remotePort";
        static final String QUERY_STRING = "queryString";
        static final String URI = "uri";
        static final String ACCEPT = "accept";
        static final String LOCAL_HOST = "host";
        static final String ACCEPT_ENCODING = "accept-encoding";
        static final String USER_AGENT = "user-agent";
        static final String PROTOCOL = "protocol";
    }
}

你可能感兴趣的:(SpringBoot结合Aop记录请求日志)