【每日阅读】2020年7月20日-SpringBoot应用中使用AOP记录接口访问日志

链接

http://www.macrozheng.com/#/technology/aop_log?id=%e5%88%87%e7%82%b9%ef%bc%88pointcut%ef%bc%89

文章截图

简评

其实这篇文章讲的aop和是不是spring boot没有关系,只要是spring应用都能用这个功能。

看了看源码,值得说的点有这么几个:

一,定义切点PointCut的表达式,限定切点只应用在Controller的public方法上了

"execution(public * com.macro.mall.controller..(..))"

二,获取web中的HttpServletRequest对象

(ServletRequestAttributes) RequestContextHolder.getRequestAttributes().getRequest();

三,获取接口description:获取方法上的ApiOperation注解的描述内容,即我们需要为每个接口维护这个描述

if (method.isAnnotationPresent(ApiOperation.class)) {
    ApiOperation log = method.getAnnotation(ApiOperation.class);
    webLog.setDescription(log.value());
}

四,获取接口入参,也就是获取web通用的RequestParam和RequestBody注解对应的参数名、值

for (int i = 0; i < parameters.length; i++) {
    //将RequestBody注解修饰的参数作为请求参数
    RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
    if (requestBody != null) {
        argList.add(args[i]);
    }
    //将RequestParam注解修饰的参数作为请求参数
    RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
    if (requestParam != null) {
        Map<String, Object> map = new HashMap<>();
        String key = parameters[i].getName();
        if (!StringUtils.isEmpty(requestParam.value())) {
            key = requestParam.value();
        }
        map.put(key, args[i]);
        argList.add(map);
    }
}

五,最后打印日志(我看的这个时候最新github代码和文章内写的不一致),这个Markers和LogStash有关

LOGGER.info(Markers.appendEntries(logMap), JSONUtil.parse(webLog).toString()); 

Markers类说明是:Convenience class for constructing various LogstashMarkers used to add fields into the logstash event。logstash事件?不太懂,应该是和把日志发送到logstash有关。

原创文章,作者:geekgao,如若转载,请注明出处:https://www.geekgao.cn/archives/2110

(0)
geekgaogeekgao博主
上一篇 2020年7月19日
下一篇 2020年7月21日

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

GitHub
分享本页
返回顶部

Warning: error_log(/usr/local/lighthouse/softwares/wordpress/wp-content/plugins/spider-analyser/#log/log-2015.txt): failed to open stream: No such file or directory in /usr/local/lighthouse/softwares/wordpress/wp-content/plugins/spider-analyser/spider.class.php on line 2900