本文介绍如何针对非 200 HTTP 响应,在独立的日志文件中记录更详细的信息,包括请求方法、路径和响应状态码。我们将探讨使用 Logback 配置实现这一目标,确保只在发生错误时才记录这些额外信息,从而避免污染常规日志。
在 Web 应用开发中,记录 HTTP 响应状态码以及相关信息对于问题排查和性能监控至关重要。特别是对于非 200 响应(例如 404 Not Found, 500 Internal Server Error),我们需要记录请求的详细信息,以便快速定位问题。本文将介绍如何使用 Logback 配置,在独立的日志文件中记录这些非 200 响应的详细信息,包括请求方法、路径和响应状态码。
使用 Logback 实现非 200 响应的独立日志记录
Logback 是一个强大的 Java 日志框架,它提供了灵活的配置选项,可以满足各种日志需求。我们可以通过配置 Logback 来实现只在发生非 200 响应时,才将请求方法、路径和响应状态码记录到独立的日志文件中。
实现思路如下:
示例 Logback 配置 (logback-spring.xml)
logs/non-200-responses.log true%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %level %logger{36} - %msg%n message.contains("response: 200") == false ACCEPT DENY ![]()
配置详解:
代码示例 (Controller)
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProductController {
private static final Logger logger = LoggerFactory.getLogger(ProductController.class);
private static final Logger non200ResponseLogger = LoggerFactory.getLogger("non200ResponseLogger");
@GetMapping("/product/{id}")
public ResponseEntity getProduct(@PathVariable("id") Long id) {
logger.info("Fetching product with id: {}", id);
if (id > 100) {
String message = String.format("method: GET, path: /product/%d, response: 404 NOT_FOUND", id);
non200ResponseLogger.warn(message);
return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND);
} else {
String message = String.format("method: GET, path: /product/%d, response: 200 OK", id);
non200ResponseLogger.warn(message); // 这条信息不会被记录到 non-200-responses.log
return new ResponseEntity<>("Product found", HttpStatus.OK);
}
}
} 代码详解:
注意事项:
总结:
通过配置 Logback,我们可以轻松地实现非 200 HTTP 响应的独立日志记录。这种方法可以帮助我们快速定位问题,提高开发和运维效率。 通过灵活的配置,我们可以根据实际需求,记录更详细的信息,例如请求头、请求体等。 此外,还可以将日志发送到远程服务器,以便进行集中管理和分析。