add logging

This commit is contained in:
a.ilin
2026-10-05 18:09:53 +03:00
parent 5920372b01
commit 1bceb8e300
5 changed files with 265 additions and 1 deletions
+1
View File
@@ -34,3 +34,4 @@ replay_pid*
/auth-keys/
/postgres-data/
/keys/
/src/main/resources/application-local.yml
@@ -3,6 +3,7 @@ package ru.gorodar.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;
import ru.gorodar.integration.RestClientLoggingInterceptor;
/**
* Бин-строитель RestClient для интеграций (open_cv). В Boot 4 автоконфигурация
@@ -14,6 +15,7 @@ public class RestClientConfig {
@Bean
RestClient.Builder restClientBuilder() {
return RestClient.builder();
return RestClient.builder()
.requestInterceptor(new RestClientLoggingInterceptor());
}
}
@@ -0,0 +1,139 @@
package ru.gorodar.integration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* Логирование исходящих вызовов внешних сервисов (open_cv, Unisender) на уровне DEBUG,
* включается настройкой ru.gorodar.integration=debug. Текстовые тела запросов (JSON и т.п.)
* логируются целиком с усечением до 8 КБ, multipart — по частям: текстовые части полностью,
* бинарные — размером. Заголовки не логируются, в них лежат API-ключи. Учтите, что в DEBUG
* попадает и текст писем с одноразовыми кодами — не включайте этот уровень в проде.
*/
@Slf4j
public class RestClientLoggingInterceptor implements ClientHttpRequestInterceptor {
private static final int MAX_TEXT_LOG_CHARS = 8 * 1024;
private static final byte[] HEADER_BODY_SEPARATOR = "\r\n\r\n".getBytes(StandardCharsets.ISO_8859_1);
private static final Pattern PART_NAME = Pattern.compile("name=\"([^\"]+)\"");
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
if (log.isDebugEnabled()) {
log.debug("--> {} {} {}", request.getMethod(), request.getURI(), describeBody(request, body));
}
long start = System.nanoTime();
try {
ClientHttpResponse response = execution.execute(request, body);
log.debug("<-- {} {} ({} ms)", response.getStatusCode().value(), request.getURI(),
(System.nanoTime() - start) / 1_000_000);
return response;
} catch (IOException e) {
log.debug("--x {} {} failed: {} ({} ms)", request.getMethod(), request.getURI(), e,
(System.nanoTime() - start) / 1_000_000);
throw e;
}
}
private String describeBody(HttpRequest request, byte[] body) {
if (body.length == 0) {
return "(no body)";
}
MediaType contentType = request.getHeaders().getContentType();
if (contentType == null) {
return "(body " + body.length + " bytes)";
}
if (contentType.isCompatibleWith(MediaType.MULTIPART_FORM_DATA)) {
return describeMultipart(contentType, body);
}
if (isTextual(contentType)) {
return "body: " + asText(body, 0, body.length);
}
return "(binary body " + body.length + " bytes, " + contentType + ")";
}
private static boolean isTextual(MediaType contentType) {
return "text".equals(contentType.getType())
|| contentType.isCompatibleWith(MediaType.APPLICATION_JSON)
|| contentType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED)
|| contentType.getSubtype().endsWith("+xml");
}
private String describeMultipart(MediaType contentType, byte[] body) {
try {
String boundary = contentType.getParameter("boundary");
if (boundary == null) {
return "(multipart body " + body.length + " bytes)";
}
byte[] delimiter = ("--" + boundary).getBytes(StandardCharsets.ISO_8859_1);
List<String> parts = new ArrayList<>();
int pos = indexOf(body, delimiter, 0);
while (pos >= 0) {
int headersStart = pos + delimiter.length;
int next = indexOf(body, delimiter, headersStart);
if (next < 0) {
break;
}
int headerEnd = indexOf(body, HEADER_BODY_SEPARATOR, headersStart);
int contentEnd = next - 2; // \r\n перед следующей границей
if (headerEnd < 0 || headerEnd + 4 > contentEnd) {
break;
}
String headers = new String(body, headersStart, headerEnd - headersStart, StandardCharsets.UTF_8);
var nameMatcher = PART_NAME.matcher(headers);
String name = nameMatcher.find() ? nameMatcher.group(1) : "part";
int contentStart = headerEnd + 4;
String value = isPrintable(body, contentStart, contentEnd)
? asText(body, contentStart, contentEnd)
: "<binary " + (contentEnd - contentStart) + " bytes>";
parts.add(name + "=" + value);
pos = next;
}
return "multipart body: [" + String.join(", ", parts) + "]";
} catch (Exception e) {
return "(multipart body " + body.length + " bytes)";
}
}
private static boolean isPrintable(byte[] data, int from, int to) {
for (int i = from; i < to; i++) {
byte b = data[i];
if (b != '\t' && b != '\n' && b != '\r' && b < 0x20) {
return false;
}
}
return true;
}
private static String asText(byte[] data, int from, int to) {
String text = new String(data, from, to - from, StandardCharsets.UTF_8);
if (text.length() > MAX_TEXT_LOG_CHARS) {
return text.substring(0, MAX_TEXT_LOG_CHARS) + " ... (truncated, " + text.length() + " chars total)";
}
return text;
}
private static int indexOf(byte[] data, byte[] pattern, int from) {
search:
for (int i = Math.max(from, 0); i <= data.length - pattern.length; i++) {
for (int j = 0; j < pattern.length; j++) {
if (data[i + j] != pattern[j]) {
continue search;
}
}
return i;
}
return -1;
}
}
+7
View File
@@ -54,6 +54,13 @@ gorodar:
path-style-access: true
presign-ttl: 1h
logging:
level:
# DEBUG включает логирование исходящих вызовов внешних сервисов (open_cv, Unisender)
ru.gorodar.integration: debug
# DEBUG-логи обращений к S3/MinIO (AWS SDK)
# software.amazon.awssdk.request: debug
management:
endpoints:
web:
@@ -0,0 +1,115 @@
package ru.gorodar.integration;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.mock.http.client.MockClientHttpRequest;
import org.springframework.mock.http.client.MockClientHttpResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
class RestClientLoggingInterceptorTest {
private final RestClientLoggingInterceptor interceptor = new RestClientLoggingInterceptor();
private Logger logger;
private ListAppender<ILoggingEvent> appender;
@BeforeEach
void attachAppender() {
logger = (Logger) LoggerFactory.getLogger(RestClientLoggingInterceptor.class);
appender = new ListAppender<>();
appender.start();
logger.addAppender(appender);
logger.setLevel(Level.DEBUG);
}
@AfterEach
void detachAppender() {
logger.detachAppender(appender);
logger.setLevel(null);
}
@Test
void textualBodyLoggedFully() throws IOException {
MockClientHttpRequest request = request(HttpMethod.POST, "https://mail.example/send");
request.getHeaders().setContentType(MediaType.APPLICATION_JSON);
interceptor.intercept(request, "{\"message\":{\"subject\":\"Код\"}}".getBytes(StandardCharsets.UTF_8),
(req, body) -> new MockClientHttpResponse(new byte[0], 200));
assertThat(messages()).anySatisfy(message -> assertThat(message)
.contains("body: {\"message\":{\"subject\":\"Код\"}}"));
}
@Test
void multipartBinaryPartsAsSizeAndTextPartsAsText() throws IOException {
String boundary = "gwKfbBoundary42";
byte[] binary = {0x00, (byte) 0xFF, (byte) 0xD8, 0x42};
ByteArrayOutputStream body = new ByteArrayOutputStream();
body.writeBytes(("--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"image\"; filename=\"reference.jpg\"\r\n"
+ "Content-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.ISO_8859_1));
body.writeBytes(binary);
body.writeBytes(("\r\n--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"settings\"\r\n\r\n"
+ "{\"profile\":\"sift\"}\r\n"
+ "--" + boundary + "--\r\n").getBytes(StandardCharsets.ISO_8859_1));
MockClientHttpRequest request = request(HttpMethod.POST, "http://localhost:8000/api/v1/features");
request.getHeaders().setContentType(MediaType.parseMediaType("multipart/form-data; boundary=" + boundary));
interceptor.intercept(request, body.toByteArray(),
(req, b) -> new MockClientHttpResponse(new byte[0], 200));
assertThat(messages()).anySatisfy(message -> assertThat(message)
.contains("multipart body: [image=<binary 4 bytes>, settings={\"profile\":\"sift\"}]"));
}
@Test
void emptyBodyMarked() throws IOException {
MockClientHttpRequest request = request(HttpMethod.GET, "http://localhost:8000/api/v1/features");
interceptor.intercept(request, new byte[0],
(req, body) -> new MockClientHttpResponse(new byte[0], 200));
assertThat(messages()).anySatisfy(message -> assertThat(message).contains("(no body)"));
}
@Test
void failureLoggedAndRethrown() {
MockClientHttpRequest request = request(HttpMethod.POST, "http://localhost:8000/api/v1/verify");
request.getHeaders().setContentType(MediaType.APPLICATION_JSON);
IOException failure = new IOException("Connection refused");
assertThrows(IOException.class, () ->
interceptor.intercept(request, "{}".getBytes(StandardCharsets.UTF_8),
(req, body) -> { throw failure; }));
assertThat(messages()).anySatisfy(message -> assertThat(message)
.contains("--x POST http://localhost:8000/api/v1/verify")
.contains("java.io.IOException: Connection refused"));
}
private MockClientHttpRequest request(HttpMethod method, String uri) {
return new MockClientHttpRequest(method, URI.create(uri));
}
private List<String> messages() {
return appender.list.stream().map(ILoggingEvent::getFormattedMessage).toList();
}
}