You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

160 lines
6.1 KiB

package common.ecommerce.shared.audit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
/**
* 基于 SLF4J 的默认观察者:成功打 INFO,失败打 WARN。
*
* <p>适合「先把调用链看清」的起步阶段;需要落库审计或接监控时,
* 换成一个写 {@code IdempotencyStore} / 数据库 / MQ 的 {@link CallObserver} 即可。</p>
*
* <p>日志里不包含凭证与报文;凭据只由 {@code ChannelConnection.toString()} 打指纹。</p>
*
* <p><b>时间显示</b>:{@link CallRecord} 内部始终是 UTC;这里只负责格式化。
* 时区取值优先级:</p>
* <ol>
* <li>构造时显式传入的 {@link ZoneId}(推荐,由宿主从配置/环境读取);</li>
* <li>缺省用 {@link ZoneId#systemDefault()},即 JVM 默认时区
* (受 {@code -Duser.timezone}、{@code TZ} 环境变量、容器时区影响)。</li>
* </ol>
*
* <p>注意:容器/CI 里 {@code systemDefault()} 通常是 UTC。想固定成本地时间,
* 建议显式传 {@code ZoneId.of("Asia/Shanghai")},而不是依赖运行环境。</p>
*/
public final class Slf4jCallObserver implements CallObserver {
/** 本类的日志器;日志绑定由宿主提供,SDK 不引入实现。 */
private static final Logger LOG = LoggerFactory.getLogger(Slf4jCallObserver.class);
/** 默认时间格式:24 小时制、精确到秒,例如 {@code 2026-11-05 08:00:00}。 */
public static final String DEFAULT_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
/** 日志展示时区,非 null。 */
private final ZoneId zone;
/** 时间格式串,非 null。 */
private final String pattern;
/** 由 {@link #pattern} + {@link #zone} 构建的格式化器,线程安全。 */
private final DateTimeFormatter formatter;
/** 使用 JVM 默认时区与默认格式 {@value #DEFAULT_TIME_PATTERN}。 */
public Slf4jCallObserver() {
this(ZoneId.systemDefault());
}
/**
* @param zone 日志展示用的时区;不要传 null
*/
public Slf4jCallObserver(ZoneId zone) {
this(zone, DEFAULT_TIME_PATTERN);
}
/**
* @param zone 日志展示用的时区;不要传 null
* @param pattern {@link DateTimeFormatter} 格式,如 {@code yyyy-MM-dd HH:mm:ss};
* 需要偏移量时用 {@code yyyy-MM-dd HH:mm:ss.SSSXXX}
*/
public Slf4jCallObserver(ZoneId zone, String pattern) {
this.zone = Objects.requireNonNull(zone, "zone");
this.pattern = Objects.requireNonNull(pattern, "pattern");
this.formatter = DateTimeFormatter.ofPattern(pattern).withZone(zone);
}
/** 当前使用的时区,便于启动日志里打印一次。 */
public ZoneId zone() {
return zone;
}
/** 当前使用的时间格式。 */
public String pattern() {
return pattern;
}
/** 按当前时区与格式渲染时间;包内可见,便于单测。 */
String format(Instant instant) {
return formatter.format(instant);
}
/**
* 每次调用结束打一行日志。
*
* <p>{@link CallRecord#failed()} 为 true 打 WARN,否则打 INFO——
* 因此 PARTIAL 也是 INFO,失败明细看行内的 {@code failed=}。</p>
*/
@Override
public void onCall(CallRecord record) {
if (record.failed()) {
LOG.warn("{}", failedLine(record));
} else {
LOG.info("{}", successLine(record));
}
}
/**
* 成功的日志行(不含级别前缀)。
*
* <p>包内可见:日志渲染与 SLF4J 绑定解耦,单测可以直接断言渲染结果,
* 不需要往 classpath 里塞日志实现。</p>
*/
String successLine(CallRecord record) {
return "sdk-call at=" + at(record.occurredAt())
+ " op=" + record.operation()
+ providerFields(record)
+ " cost=" + record.durationMillis() + "ms"
+ " result=" + record.resultCount()
+ " failed=" + record.failedCount()
+ " code=" + record.resultCode()
+ " params=" + record.params();
}
/**
* 失败的日志行(不含级别前缀)。
*
* <p>平台文案不可控,{@link #safe(String)} 会去掉换行/控制字符并截断,
* 避免一条日志被拆成多行(log forging)。</p>
*/
String failedLine(CallRecord record) {
return "sdk-call-failed at=" + at(record.occurredAt())
+ " op=" + record.operation()
+ providerFields(record)
+ " cost=" + record.durationMillis() + "ms"
+ " result=" + record.resultCount()
+ " failed=" + record.failedCount()
+ " code=" + record.resultCode()
+ " params=" + record.params()
+ " retryable=" + record.retryable()
+ " platformCode=" + record.platformCode()
+ " platformRequestId=" + record.platformRequestId()
+ " error=" + record.errorType() + ": " + safe(record.errorMessage());
}
/** 拼公共维度字段:provider / platform / 两侧店铺 ID / 我方链路 ID。 */
private static String providerFields(CallRecord record) {
return " provider=" + record.provider()
+ " platform=" + record.platform()
+ " omsStoreId=" + record.omsStoreId()
+ " storeId=" + record.externalStoreId()
+ " requestId=" + record.requestId();
}
/** 按当前时区与格式渲染时间。 */
private String at(Instant instant) {
return format(instant);
}
/**
* 平台文案不可控,去掉换行/控制字符并截断,避免一条日志被拆成多行。
*/
private static String safe(String value) {
if (value == null) {
return null;
}
String oneLine = value.replaceAll("\\p{Cntrl}", " ").trim();
return oneLine.length() <= 512 ? oneLine : oneLine.substring(0, 512) + "...";
}
}