70 lines
2.5 KiB
Go
70 lines
2.5 KiB
Go
// transport_logging.go WMS→MES 全量 HTTP 交互日志(2026-11-16 联调)。
|
|
// http.RoundTripper 装饰器:挂在 Client.hc 与 Ping 临时 client 上,
|
|
// 所有出口(getJSON/postJSON/Ping/LookupFinishedBySN/ListMaterialRequests 等)自动全覆盖。
|
|
// 记录:请求方法/完整URL/请求体(截断)、响应状态码/响应体(截断)、传输错误。
|
|
// 前缀 [WMS→MES]。
|
|
package mesclient
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
|
|
"bj_power_wms/internal/netutil"
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
// commTag 本机 IP 前缀(进程启动解析一次),断网排查时可一眼看出日志来自哪台机器。
|
|
var commTag = netutil.Tag()
|
|
|
|
// loggingTransport 日志装饰 transport。
|
|
type loggingTransport struct{ base http.RoundTripper }
|
|
|
|
// FailHook MES 通讯失败钩子(2026-11-16):仅【传输层失败】(连不上/超时/断连)触发,
|
|
// HTTP 非 2xx 与业务码非 0 属正常业务响应不触发。main 启动时装配(落预警中心),
|
|
// 去重由回调实现方负责(窗口去重),本层只负责在错误发生时通知。
|
|
var FailHook func(ctx context.Context, method, url string, err error)
|
|
|
|
func newLoggingTransport() *loggingTransport {
|
|
return &loggingTransport{base: http.DefaultTransport}
|
|
}
|
|
|
|
func (t *loggingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
u := req.URL.String()
|
|
var reqBody []byte
|
|
if req.Body != nil {
|
|
reqBody, _ = io.ReadAll(req.Body)
|
|
_ = req.Body.Close()
|
|
req.Body = io.NopCloser(bytes.NewReader(reqBody))
|
|
}
|
|
logx.WithContext(req.Context()).Infof("[WMS→MES]"+commTag+" --> %s %s body=%s", req.Method, u, truncateLogBytes(reqBody))
|
|
|
|
resp, err := t.base.RoundTrip(req)
|
|
if err != nil {
|
|
logx.WithContext(req.Context()).Errorf("[WMS→MES]"+commTag+" <-- transport error %s err=%v", u, err)
|
|
if FailHook != nil {
|
|
FailHook(req.Context(), req.Method, u, err)
|
|
}
|
|
return resp, err
|
|
}
|
|
raw, rerr := io.ReadAll(resp.Body)
|
|
_ = resp.Body.Close()
|
|
if rerr != nil {
|
|
logx.WithContext(req.Context()).Errorf("[WMS→MES]"+commTag+" <-- read body error %s status=%d err=%v", u, resp.StatusCode, rerr)
|
|
}
|
|
resp.Body = io.NopCloser(bytes.NewReader(raw))
|
|
logx.WithContext(req.Context()).Infof("[WMS→MES]"+commTag+" <-- HTTP %d %s body=%s", resp.StatusCode, u, truncateLogBytes(raw))
|
|
return resp, nil
|
|
}
|
|
|
|
// truncateLogBytes 日志防刷爆:超 2000 字节截断。
|
|
func truncateLogBytes(b []byte) string {
|
|
const max = 2000
|
|
if len(b) <= max {
|
|
return string(b)
|
|
}
|
|
return string(b[:max]) + fmt.Sprintf("...(截断,共%d字节)", len(b))
|
|
}
|