package com.vincent.rsf.httpaudit.service;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.SerializationFeature;
|
import com.vincent.rsf.httpaudit.entity.HttpAuditLog;
|
import com.vincent.rsf.httpaudit.props.HttpAuditProperties;
|
import lombok.RequiredArgsConstructor;
|
import lombok.extern.slf4j.Slf4j;
|
import org.opensearch.client.Request;
|
import org.opensearch.client.ResponseException;
|
import org.opensearch.client.RestClient;
|
|
import java.time.ZoneOffset;
|
import java.util.LinkedHashMap;
|
import java.util.Map;
|
import java.util.UUID;
|
|
/**
|
* 写入 OpenSearch 索引
|
*/
|
@Slf4j
|
@RequiredArgsConstructor
|
public class OpenSearchHttpAuditLogSink implements HttpAuditLogSink {
|
|
private static final ObjectMapper JSON = new ObjectMapper()
|
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
|
private final RestClient restClient;
|
private final HttpAuditProperties props;
|
|
@Override
|
public void write(HttpAuditLog entity) {
|
try {
|
String index = props.getOpenSearch().getIndexName();
|
String docId = entity.getId() != null ? String.valueOf(entity.getId()) : UUID.randomUUID().toString();
|
String path = "/" + index + "/_doc/" + docId + "?refresh=false";
|
Request request = new Request("PUT", path);
|
request.setJsonEntity(JSON.writeValueAsString(toDocument(entity)));
|
restClient.performRequest(request);
|
} catch (ResponseException ex) {
|
int code = ex.getResponse() != null ? ex.getResponse().getStatusLine().getStatusCode() : -1;
|
log.error("http-audit OpenSearch 写入失败 uri={} status={}", entity.getUri(), code, ex);
|
} catch (Throwable t) {
|
log.error("http-audit OpenSearch 写入失败 uri={}", entity.getUri(), t);
|
}
|
}
|
|
private static Map<String, Object> toDocument(HttpAuditLog e) {
|
Map<String, Object> m = new LinkedHashMap<>();
|
m.put("id", e.getId());
|
m.put("service_name", e.getServiceName());
|
m.put("scope_type", e.getScopeType());
|
m.put("uri", e.getUri());
|
m.put("io_direction", e.getIoDirection());
|
m.put("method", e.getMethod());
|
m.put("function_desc", e.getFunctionDesc());
|
m.put("query_string", e.getQueryString());
|
m.put("request_body", e.getRequestBody());
|
m.put("response_body", e.getResponseBody());
|
m.put("response_truncated", e.getResponseTruncated());
|
m.put("http_status", e.getHttpStatus());
|
m.put("ok_flag", e.getOkFlag());
|
m.put("spend_ms", e.getSpendMs());
|
m.put("client_ip", e.getClientIp());
|
m.put("error_message", e.getErrorMessage());
|
if (e.getCreateTime() != null) {
|
m.put("create_time", e.getCreateTime().toInstant().atOffset(ZoneOffset.UTC).toString());
|
}
|
m.put("deleted", e.getDeleted());
|
return m;
|
}
|
}
|