83 lines
2.9 KiB
Go
83 lines
2.9 KiB
Go
// transport_logging.go MES→WMS 全量 HTTP 交互日志(2026-11-16 联调)。
|
||
// 用 http.RoundTripper 装饰器实现:挂在 Client.hc 上后,所有出口函数
|
||
// (post/get/postSemi/ExportProductTypes 等)的每次请求自动落日志,无需逐点插桩。
|
||
// 记录:请求方法/完整URL/请求体(截断 2000 字节)、响应状态码/响应体(截断 2000 字节)、传输错误。
|
||
// 前缀 [MES→WMS],grep 即可定位;响应体读出后用 NopCloser 回填,不影响调用方解析。
|
||
package wmsclient
|
||
|
||
import (
|
||
"bytes"
|
||
"context"
|
||
"io"
|
||
"net/http"
|
||
|
||
"bj_power_mes/internal/netutil"
|
||
"github.com/zeromicro/go-zero/core/logx"
|
||
)
|
||
|
||
// commTag 本机 IP 前缀(进程启动解析一次),断网排查时可一眼看出日志来自哪台机器。
|
||
var commTag = netutil.Tag()
|
||
|
||
// loggingTransport 日志装饰 transport。
|
||
type loggingTransport struct{ base http.RoundTripper }
|
||
|
||
// FailHook WMS 通讯失败钩子(2026-11-16):仅【传输层失败】(连不上/超时/断连)触发,
|
||
// HTTP 非 2xx 与业务码非 0 属正常业务响应不触发。main 启动时装配(落预警中心),包外勿随意设置。
|
||
// 去重由回调实现方负责(CreateAlertDedup 窗口去重),本层只负责在错误发生时通知。
|
||
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("[MES→WMS]"+commTag+"--> %s %s body=%s", req.Method, u, truncateLogBytes(reqBody))
|
||
|
||
resp, err := t.base.RoundTrip(req)
|
||
if err != nil {
|
||
logx.WithContext(req.Context()).Errorf("[MES→WMS]"+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("[MES→WMS]"+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("[MES→WMS]"+commTag+"<-- HTTP %d %s body=%s", resp.StatusCode, u, truncateLogBytes(raw))
|
||
return resp, nil
|
||
}
|
||
|
||
// truncateLogBytes 日志防刷爆:超 2000 字节截断(xlsx 导出等大响应只记头段)。
|
||
func truncateLogBytes(b []byte) string {
|
||
const max = 2000
|
||
if len(b) <= max {
|
||
return string(b)
|
||
}
|
||
return string(b[:max]) + "...(截断,共" + itoaLen(len(b)) + "字节)"
|
||
}
|
||
|
||
func itoaLen(n int) string {
|
||
if n == 0 {
|
||
return "0"
|
||
}
|
||
var buf [20]byte
|
||
i := len(buf)
|
||
for n > 0 {
|
||
i--
|
||
buf[i] = byte('0' + n%10)
|
||
n /= 10
|
||
}
|
||
return string(buf[i:])
|
||
}
|