在项目 pom.xml 文件中添加依赖:

<!-- aop 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency> <!-- 用于日志切面中,以 json 格式打印出入参 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.primitives.Bytes;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors; @Aspect
@Component
@EnableAspectJAutoProxy
@Slf4j
public class LogAop {
// @Pointcut("@annotation(ExtendPoint)") //ExtendPoint为自定义的注解
@Pointcut("execution(* com.demo.wode.controller.*Controller.*(..))") //表示controller目录下的所有类名包含Controller的类中所有的公有方法
public void excudeService() {
} @Around("excudeService()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
HttpServletRequest request = servletRequestAttributes.getRequest();
log.info("=======================aop log start===================================="); Object[] args = joinPoint.getArgs();
List<Object> logArgs = Arrays.asList(args).stream()
.filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse)))
.collect(Collectors.toList()); log.info("======request begin=====");
log.info("url : {} ", request.getRequestURL());
log.info("uri : {} ", request.getRequestURI());
log.info("method : {} ", request.getMethod());
log.info("param : {} ", JSON.toJSONString(logArgs)); Object result;
try {
result = joinPoint.proceed();
log.info("=====request end=====");
log.info("result : {}", JSON.toJSONString(result));
} catch (Exception e) {
StackTraceElement[] stackTraceElements = e.getStackTrace();
byte[] bytes = new byte[]{};
for (StackTraceElement element : stackTraceElements) {
byte[] byteArray = element.toString().getBytes();
bytes = Bytes.concat(bytes, byteArray);
}
bytes = Bytes.concat(("*exception*" + e.getMessage() + "*exception*").getBytes(), bytes);
e.printStackTrace();
log.info("=======================aop log end with exception====================================");
throw e;
}
log.info("=======================aop log end===================================="); return result;
} }

第二种:
package com.gaoxi.handle;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; /**
* @Author 大闲人柴毛毛
* @Date 2017/10/29 下午12:58
* REST接口统一的日志处理
*/
@ControllerAdvice
@ResponseBody
public class LogHandle { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Pointcut("execution(public * com.gaoxi.controller..*.*(..))")
public void restLog(){} @Around("restLog()")
public void doAround(ProceedingJoinPoint joinPoint) throws Throwable { // 生成本次请求时间戳
String timestamp = System.currentTimeMillis()+""; RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
HttpServletRequest request = sra.getRequest(); String url = request.getRequestURL().toString();
String method = request.getMethod();
String uri = request.getRequestURI();
String queryString = request.getQueryString();
logger.info(timestamp + ", url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString); // result的值就是被拦截方法的返回值
Object result = joinPoint.proceed();
logger.info(timestamp + " , " + result.toString());
} }
												

springboot --AopLog的更多相关文章

  1. Spring Boot从入门到实战:集成AOPLog来记录接口访问日志

    日志是一个Web项目中必不可少的部分,借助它我们可以做许多事情,比如问题排查.访问统计.监控告警等.一般通过引入slf4j的一些实现框架来做日志功能,如log4j,logback,log4j2,其性能 ...

  2. 【Java分享客栈】超简洁SpringBoot使用AOP统一日志管理-纯干货干到便秘

    前言 请问今天您便秘了吗?程序员坐久了真的会便秘哦,如果偶然点进了这篇小干货,就麻烦您喝杯水然后去趟厕所一边用左手托起对准嘘嘘,一边用右手滑动手机看完本篇吧. 实现 本篇AOP统一日志管理写法来源于国 ...

  3. 解决 Springboot Unable to build Hibernate SessionFactory @Column命名不起作用

    问题: Springboot启动报错: Caused by: org.springframework.beans.factory.BeanCreationException: Error creati ...

  4. 【微框架】Maven +SpringBoot 集成 阿里大鱼 短信接口详解与Demo

    Maven+springboot+阿里大于短信验证服务 纠结点:Maven库没有sdk,需要解决 Maven打包找不到相关类,需要解决 ps:最近好久没有写点东西了,项目太紧,今天来一篇 一.本文简介 ...

  5. Springboot搭建web项目

    最近因为项目需要接触了springboot,然后被其快速零配置的特点惊呆了.关于springboot相关的介绍我就不赘述了,大家自行百度google. 一.pom配置 首先,建立一个maven项目,修 ...

  6. Java——搭建自己的RESTful API服务器(SpringBoot、Groovy)

    这又是一篇JavaWeb相关的博客,内容涉及: SpringBoot:微框架,提供快速构建服务的功能 SpringMVC:Struts的替代者 MyBatis:数据库操作库 Groovy:能与Java ...

  7. 解决 SpringBoot 没有主清单属性

    问题:SpringBoot打包成jar后运行提示没有主清单属性 解决:补全maven中的bulid信息 <plugin> <groupId>org.springframewor ...

  8. SpringBoot中yaml配置对象

    转载请在页首注明作者与出处 一:前言 YAML可以代替传统的xx.properties文件,但是它支持声明map,数组,list,字符串,boolean值,数值,NULL,日期,基本满足开发过程中的所 ...

  9. springboot 学习资源推荐

    springboot 是什么?对于构建生产就绪的Spring应用程序有一个看法. Spring Boot优先于配置的惯例,旨在让您尽快启动和运行.(这是springboot的官方介绍) 我们为什么要学 ...

随机推荐

  1. 实验吧--web--你真的会php吗

    ---恢复内容开始--- 实验吧的一道题php审计题.拉下来写一写. http://ctf5.shiyanbar.com/web/PHP/index.php 打开之后说have fun 那就抓包来看看 ...

  2. 个人永久性免费-Excel催化剂功能第40波-工资、年终奖个人所得税计算函数

    学Excel的表哥表姐们必定有接触过个人所得税的案例学习,在计算个人所得税这个需求上,大家的层次也是很多种多样,当然Excel催化剂推荐的方式仍然是经过封装后的简单明了的自定义函数的方式,此篇已为财务 ...

  3. python 2.7 - 3.5 升级之路 (二) : 语法与类库升级

    背景 在上一篇博文中,我们为升级python 2 -> 3已经做了一些准备.在这篇中,我们将针对语法与类库这两个方面进行讨论. 关于语法 1. print 在python3中, print 已经 ...

  4. Scala数据结构

    Scala数据结构 主要的集合特质 Scala同时支持可变集合和不可变集合,优先采用不可变集合.集合主要分为三大类:序列(List),集(set),映射(map).所有的集合都扩展自Iterable特 ...

  5. Kafka配置信息

    Kafka配置信息 broker配置信息 属性 默认值 描述 broker.id 必填参数,broker的唯一标识 log.dirs /tmp/kafka-logs Kafka数据存放的目录.可以指定 ...

  6. cron 表达式的格式 了解

    cron 表达式的格式 Quartz cron 表达式的格式十分类似于 UNIX cron 格式,但还是有少许明显的区别.区别之一就是 Quartz 的格式向下支持到秒级别的计划,而 UNIX cro ...

  7. [leetcode] 20. Valid Parentheses (easy)

    原题链接 匹配括号 思路: 用栈,遍历过程中,匹配的成对出栈:结束后,栈空则对,栈非空则错. Runtime: 4 ms, faster than 99.94% of Java class Solut ...

  8. 架构师小跟班:SSL证书免费申请及部署,解决页面样式错乱问题完整攻略

    申请证书 1.登录阿里云控制台,产品与服务,选择SSL证书 2.进入SSL证书页面,点击“购买证书”,选择免费1年的证书类型,点击“立即购买” 3.返回SSL证书页面,可以看到证书列表里多了一条记录 ...

  9. nginx配置目录访问&用户名密码控制

    背景 项目上需要一些共享目录让外地同事可以网页访问对应的文件,且受权限控制: 现有环境: centos nginx 你可以了解到以下内容: 配置nginx开启目录访问 并配置nginx用户名和密码进行 ...

  10. C++多小球非对心弹性碰撞(HGE引擎)

    程序是一个月前完成的,之前一直没正儿八经的来整理下这个程序,感觉比较简单,不过即使简单的东西也要跟大家分享下. 源码下载:http://download.csdn.net/detail/y851716 ...