SpringBoot实战 之 接口日志篇
在本篇文章中不会详细介绍日志如何配置、如果切换另外一种日志工具之类的内容,只用于记录作者本人在工作过程中对日志的几种处理方式。
1. Debug 日志管理
在开发的过程中,总会遇到各种莫名其妙的问题,而这些问题的定位一般会使用到两种方式,第一种是通过手工 Debug 代码,第二种则是直接查看日志输出。Debug 代码这种方式只能在 IDE 下使用,一旦程序移交部署,就只能通过日志来跟踪定位了。
在测试环境下,我们无法使用 Debug 代码来定位问题,所以这时候需要记录所有请求的参数及对应的响应报文。而在 数据交互篇 中,我们将请求及响应的格式都定义成了Json,而且传输的数据还是存放在请求体里面。而请求体对应在 HttpServletRequest 里面又只是一个输入流,这样的话,就无法在过滤器或者拦截器里面去做日志记录了,而必须要等待输入流转换成请求模型后(响应对象转换成输出流前)做数据日志输出。
有目标那就好办了,只需要找到转换发生的地方就可以植入我们的日志了。通过源码的阅读,终于在 AbstractMessageConverterMethodArgumentResolver 个类中发现了我们的期望的那个地方,对于请求模型的转换,实现代码如下:
@SuppressWarnings("unchecked")
protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {
MediaType contentType;
boolean noContentType = false;
try {
contentType = inputMessage.getHeaders().getContentType();
}
catch (InvalidMediaTypeException ex) {
throw new HttpMediaTypeNotSupportedException(ex.getMessage());
}
if (contentType == null) {
noContentType = true;
contentType = MediaType.APPLICATION_OCTET_STREAM;
}
Class<?> contextClass = (parameter != null ? parameter.getContainingClass() : null);
Class<T> targetClass = (targetType instanceof Class ? (Class<T>) targetType : null);
if (targetClass == null) {
ResolvableType resolvableType = (parameter != null ?
ResolvableType.forMethodParameter(parameter) : ResolvableType.forType(targetType));
targetClass = (Class<T>) resolvableType.resolve();
}
HttpMethod httpMethod = ((HttpRequest) inputMessage).getMethod();
Object body = NO_VALUE;
try {
inputMessage = new EmptyBodyCheckingHttpInputMessage(inputMessage);
for (HttpMessageConverter<?> converter : this.messageConverters) {
Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass();
if (converter instanceof GenericHttpMessageConverter) {
GenericHttpMessageConverter<?> genericConverter = (GenericHttpMessageConverter<?>) converter;
if (genericConverter.canRead(targetType, contextClass, contentType)) {
if (logger.isDebugEnabled()) {
logger.debug("Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]");
}
if (inputMessage.getBody() != null) {
inputMessage = getAdvice().beforeBodyRead(inputMessage, parameter, targetType, converterType);
body = genericConverter.read(targetType, contextClass, inputMessage);
body = getAdvice().afterBodyRead(body, inputMessage, parameter, targetType, converterType);
}
else {
body = getAdvice().handleEmptyBody(null, inputMessage, parameter, targetType, converterType);
}
break;
}
}
else if (targetClass != null) {
if (converter.canRead(targetClass, contentType)) {
if (logger.isDebugEnabled()) {
logger.debug("Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]");
}
if (inputMessage.getBody() != null) {
inputMessage = getAdvice().beforeBodyRead(inputMessage, parameter, targetType, converterType);
body = ((HttpMessageConverter<T>) converter).read(targetClass, inputMessage);
body = getAdvice().afterBodyRead(body, inputMessage, parameter, targetType, converterType);
}
else {
body = getAdvice().handleEmptyBody(null, inputMessage, parameter, targetType, converterType);
}
break;
}
}
}
}
catch (IOException ex) {
throw new HttpMessageNotReadableException("Could not read document: " + ex.getMessage(), ex);
}
if (body == NO_VALUE) {
if (httpMethod == null || !SUPPORTED_METHODS.contains(httpMethod) ||
(noContentType && inputMessage.getBody() == null)) {
return null;
}
throw new HttpMediaTypeNotSupportedException(contentType, this.allSupportedMediaTypes);
}
return body;
}
上面的代码中有一处非常重要的地方,那就在在数据转换前后都存在 Advice 相关的方法调用,显然,只需要在 Advice 里面完成日志记录就可以了,下面开始实现自定义 Advice。
首先,请求体日志切面 LogRequestBodyAdvice 实现如下:
@ControllerAdvice
public class LogRequestBodyAdvice implements RequestBodyAdvice { private Logger logger = LoggerFactory.getLogger(LogRequestBodyAdvice.class); @Override
public boolean supports(MethodParameter methodParameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
return true;
} @Override
public Object handleEmptyBody(Object body, HttpInputMessage inputMessage,
MethodParameter parameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
return body;
} @Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage,
MethodParameter parameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
return inputMessage;
} @Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage,
MethodParameter parameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
Method method = parameter.getMethod();
String classMappingUri = getClassMappingUri(method.getDeclaringClass());
String methodMappingUri = getMethodMappingUri(method);
if (!methodMappingUri.startsWith("/")) {
methodMappingUri = "/" + methodMappingUri;
}
logger.debug("uri={} | requestBody={}", classMappingUri + methodMappingUri, JSON.toJSONString(body));
return body;
} private String getMethodMappingUri(Method method) {
RequestMapping methodDeclaredAnnotation = method.getDeclaredAnnotation(RequestMapping.class);
return methodDeclaredAnnotation == null ? "" : getMaxLength(methodDeclaredAnnotation.value());
} private String getClassMappingUri(Class<?> declaringClass) {
RequestMapping classDeclaredAnnotation = declaringClass.getDeclaredAnnotation(RequestMapping.class);
return classDeclaredAnnotation == null ? "" : getMaxLength(classDeclaredAnnotation.value());
} private String getMaxLength(String[] strings) {
String methodMappingUri = "";
for (String string : strings) {
if (string.length() > methodMappingUri.length()) {
methodMappingUri = string;
}
}
return methodMappingUri;
}
}
得到日志记录如下:
2017-05-02 22:48:15.435 DEBUG 888 --- [nio-8080-exec-1] c.q.funda.advice.LogRequestBodyAdvice : uri=/sys/user/login |
requestBody={"password":"123","username":"123"}
对应的,响应体日志切面 LogResponseBodyAdvice 实现如下:
@ControllerAdvice
public class LogResponseBodyAdvice implements ResponseBodyAdvice { private Logger logger = LoggerFactory.getLogger(LogResponseBodyAdvice.class); @Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
} @Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
logger.debug("uri={} | responseBody={}", request.getURI().getPath(), JSON.toJSONString(body));
return body;
}
}
得到日志记录如下:
2017-05-02 22:48:15.520 DEBUG 888 --- [nio-8080-exec-1] c.q.funda.advice.LogResponseBodyAdvice : uri=/sys/user/login |
responseBody={"code":10101,"msg":"手机号格式不合法"}
2. 异常日志管理
Debug 日志只适用于开发及测试阶段,一般应用部署生产,鉴于日志里面的敏感信息过多,往往只会在程序出现异常时输出明细的日志信息,在 ExceptionHandler 标注的方法里面输入异常日志无疑是最好的,但摆在面前的一个问题是,如何将 @RequestBody 绑定的 Model 传递给异常处理方法?我想到的是通过 ThreadLocal 这个线程本地变量来存储每一次请求的 Model,这样就可以贯穿整个请求处理流程,下面使用 ThreadLocal 来协助完成异常日志的记录。
在绑定时,将绑定 Model 有存放到 ThreadLocal:
@RestController
@RequestMapping("/sys/user")
public class UserController { public static final ThreadLocal<Object> MODEL_HOLDER = new ThreadLocal<>(); @InitBinder
public void initBinder(WebDataBinder webDataBinder) {
MODEL_HOLDER.set(webDataBinder.getTarget());
} }
异常处理时,从 ThreadLocal 中取出变量,并做相应的日志输出:
@ControllerAdvice
@ResponseBody
public class ExceptionHandlerAdvice { private Logger logger = LoggerFactory.getLogger(ExceptionHandlerAdvice.class); @ExceptionHandler(Exception.class)
public Result handleException(Exception e, HttpServletRequest request) {
logger.error("uri={} | requestBody={}", request.getRequestURI(),
JSON.toJSONString(UserController.MODEL_HOLDER.get()));
return new Result(ResultCode.WEAK_NET_WORK);
} }
当异常产生时,输出日志如下:
2017-05-03 21:46:07.177 ERROR 633 --- [nio-8080-exec-1] c.q.funda.advice.ExceptionHandlerAdvice : uri=/sys/user/login |
requestBody={"password":"123","username":"13632672222"}
注意:当 Mapping 方法中带有多个参数时,需要将 @RequestBody 绑定的变量当作方法的最后一个参数,否则 ThreadLocal 中的值将会被其它值所替换。如果需要输出 Mapping 方法中所有参数,可以在 ThreadLocal 里面存放一个 Map 集合。
项目的 github 地址:https://github.com/qchery/funda
原文地址:http://blog.csdn.net/chinrui/article/details/71056847
SpringBoot实战 之 接口日志篇的更多相关文章
- Spring Boot 2.x(十一):AOP实战--打印接口日志
接口日志有啥用 在我们日常的开发过程中,我们可以通过接口日志去查看这个接口的一些详细信息.比如客户端的IP,客户端的类型,响应的时间,请求的类型,请求的接口方法等等,我们可以对这些数据进行统计分析,提 ...
- SpringBoot实战 之 异常处理篇
在互联网时代,我们所开发的应用大多是直面用户的,程序中的任何一点小疏忽都可能导致用户的流失,而程序出现异常往往又是不可避免的,那该如何减少程序异常对用户体验的影响呢?其实方法很简单,对异常进行捕获,然 ...
- SpringBoot实战之异常处理篇
在互联网时代,我们所开发的应用大多是直面用户的,程序中的任何一点小疏忽都可能导致用户的流失,而程序出现异常往往又是不可避免的,那该如何减少程序异常对用户体验的影响呢?其实方法很简单,对异常进行捕获,然 ...
- SpringSecurity权限管理系统实战—二、日志、接口文档等实现
系列目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战 ...
- JAVAEE——SpringBoot日志篇:日志框架SLF4j、日志配置、日志使用、切换日志框架
Spring Boot 日志篇 1.日志框架(故事引入) 小张:开发一个大型系统: 1.System.out.println(""):将关键数据打印在控制台:去掉?写在一个文件 ...
- SpringBoot实战(四)获取接口请求中的参数(@PathVariable,@RequestParam,@RequestBody)
上一篇SpringBoot实战(二)Restful风格API接口中写了一个控制器,获取了前端请求的参数,现在我们就参数的获取与校验做一个介绍: 一:获取参数 SpringBoot提供的获取参数注解包括 ...
- SpringBoot实战(二)Restful风格API接口
在上一篇SpringBoot实战(一)HelloWorld的基础上,编写一个Restful风格的API接口: 1.根据MVC原则,创建一个简单的目录结构,包括controller和entity,分别创 ...
- springboot实战开发全套教程,让开发像搭积木一样简单!Github星标已上10W+!
前言 先说一下,这份教程在github上面星标已上10W,下面我会一一给大家举例出来全部内容,原链接后面我会发出来!首先我讲一下接下来我们会讲到的知识和技术,对比讲解了多种同类技术的使用手日区别,大家 ...
- apollo客户端springboot实战(四)
1. apollo客户端springboot实战(四) 1.1. 前言 经过前几张入门学习,基本已经完成了apollo环境的搭建和简单客户端例子,但我们现在流行的通常是springboot的客户端 ...
随机推荐
- Java集合分析
Java集合分析 前言 从开始接触Java的时候, 就在强调的一个重要版块, 集合. 终于能够开始对它的源码进行分析, 理解, 如果不懂得背后的思想, 那么读懂代码, 也仅仅是读懂了 if else ...
- Java8内存模型—永久代(PermGen)和元空间(Metaspace)(转)
Java8内存模型—永久代(PermGen)和元空间(Metaspace) 查看原文点击传送门:http://www.cnblogs.com/paddix/p/5309550.html 提示:本文做了 ...
- easyUI中点击datagrid列标题排序
easyUI中点击datagrid的排序有两种,一种是本地的,一种是服务器的.本地的只能排序当前页,而服务器的可以对全部页进行排序.这里主要是分享下服务器排序. 1.为datagrid添加属性remo ...
- 前端自动化测试神器-Katalon的基础用法
前言 最近由于在工作中需要通过Web端的功能进行一次大批量的操作,数据量大概在5000左右,如果手动处理, 完成一条数据的操作用时在20秒左右的话,大概需要4-5个人/天的工作量(假设一天8小时的工作 ...
- ATS日志说明
在ATS日志中我们经常遇到形形色色的缓存结果码,为了更清晰地认识它们,相关资料整理到这里: TCP_HIT 请求对象的一份合法拷贝被缓存,ATS将发送该对象给client TCP_MISS 请求对象未 ...
- mysql 我们眼中的int(10)
自我总结,欢迎拍砖! 目的:定义int(3)和int(10)真的有区别吗? 论证: 1.创建student,student2表 分别定义一个student,student2表 create table ...
- 《Python网络编程》学习笔记--从例子中收获的计算机网络相关知识
从之前笔记的四个程序中(http://www.cnblogs.com/take-fetter/p/8278864.html),我们可以看出分别使用了谷歌地理编码API(对URL表示地理信息查询和如何获 ...
- es数据恢复杂记
kill -9或者断电等原因异常,es在重启后,会通过translog来进行数据恢复. 默认的恢复速度是较慢的,可以设置indices.recovery.current_streams:10增大恢复的 ...
- BZOJ 1801: [Ahoi2009]chess 中国象棋 [DP 组合计数]
http://www.lydsy.com/JudgeOnline/problem.php?id=1801 在N行M列的棋盘上,放若干个炮可以是0个,使得没有任何一个炮可以攻击另一个炮. 请问有多少种放 ...
- 一个巨low的“2048”
代码就是这样,做的不是4*4而是一个2*2 #include<stdio.h>#include<stdlib.h>#include<time.h>int main( ...