Log printing collection is a key means for debugging and locating online problems during development, and it is also a top priority. As the core module of request portal forwarding, gateway is the core module for request entrance forwarding. Reasonable and standardized log printing is very important.
- Only log printing is done here, no collection is done. The collection and summary work can be combined with ELK to monitor the log files for synchronization.
- The implementation uses gateway's GlobalFilter filter.
- The filter order of request log printing should be as low as possible.
- When printing logs, be careful to avoid confusing concurrent request logs caused by multiple printings. You can splice a large log string and print it out at once.
RequestLogFilter
Add a request input filter to print input parameter information.
@Slf4j
@Configuration
@ConditionalOnProperty(value = "log.request.enabled", havingValue = "true", matchIfMissing = true)
public class RequestLogFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
// 打印请求路径
String path = request.getPath().pathWithinApplication().value();
// 打印请求url
String requestUrl = this.getOriginalRequestUrl(exchange);
// **构建成一条长 日志,避免并发下日志错乱**
StringBuilder reqLog = new StringBuilder(200);
// 日志参数
List<Object> reqArgs = new ArrayList<>();
reqLog.append("
================ Gateway Request Start ================
");
// 打印路由添加占位符
reqLog.append("===> {}: {}
");
// 参数
String requestMethod = request.getMethodValue();
reqArgs.add(requestMethod);
reqArgs.add(requestUrl);
// 打印请求头
HttpHeaders headers = request.getHeaders();
headers.forEach((headerName, headerValue) -> {
reqLog.append("===Headers=== {}: {}
");
reqArgs.add(headerName);
//如果有token,可以先把token解析后打印出原始报文,JwtUtil替换成自己项目里工具类
if (AUTH_KEY.toLowerCase().equals(headerName)) {
String value = headerValue.get(0);
String token = JwtUtil.get