优化日志系统

This commit is contained in:
yml2213
2026-06-19 12:10:55 +08:00
parent 1805edc63a
commit 59b9dd12ef
11 changed files with 232 additions and 66 deletions
+112 -12
View File
@@ -8,6 +8,7 @@ import (
"io"
"mime/multipart"
"net/http"
"reflect"
"strconv"
"strings"
"time"
@@ -54,7 +55,7 @@ func (c *DouyuClient) fetchServerTimeOnce() (time.Time, error) {
} `json:"preExchange"`
} `json:"data"`
}
if err := c.getJSON(url, "", &result); err != nil {
if err := c.getJSON(url, "", "服务时间", &result); err != nil {
return time.Time{}, err
}
ts, err := strconv.ParseInt(result.Data.PreExchange.CurrentTime, 10, 64)
@@ -72,7 +73,7 @@ func (c *DouyuClient) Products() ([]Product, error) {
List []Product `json:"list"`
} `json:"data"`
}
if err := c.getJSON(storeHomeURL, "", &result); err != nil {
if err := c.getJSON(storeHomeURL, "", "商品列表", &result); err != nil {
return nil, err
}
if result.Error != 0 {
@@ -96,7 +97,7 @@ func (c *DouyuClient) Score(cookie string) (int, error) {
Balance int `json:"balance"`
} `json:"data"`
}
if err := c.doJSON(req, &result); err != nil {
if err := c.doJSON(req, &result, "积分余额"); err != nil {
return 0, err
}
if result.Error != 0 {
@@ -113,32 +114,41 @@ func (c *DouyuClient) GenerateCSRF(cookie string) (string, error) {
}
c.setBrowserHeaders(req, cookie)
start := time.Now()
resp, err := c.httpClient.Do(req)
if err != nil {
logNetworkError("生成CSRF", req, time.Since(start), err)
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
logNetworkError("生成CSRF", req, time.Since(start), err)
return "", err
}
if resp.StatusCode != http.StatusOK {
logNetworkHTTPError("生成CSRF", req, resp.StatusCode, time.Since(start), body)
return "", fmt.Errorf("CSRF HTTP %d: %s", resp.StatusCode, trimForLog(string(body), 120))
}
var api APIResponse
if err := json.Unmarshal(body, &api); err != nil {
logNetworkParseError("生成CSRF", req, time.Since(start), body, err)
return "", fmt.Errorf("CSRF 响应解析失败: %w", err)
}
if api.Error != 0 {
logNetworkAPIResult("生成CSRF", req, time.Since(start), api.Error, api.Msg)
return "", fmt.Errorf("CSRF 接口失败: %s", api.Msg)
}
for _, ck := range resp.Cookies() {
if ck.Name == "cvl_csrf_token" && ck.Value != "" {
logNetworkSuccess("生成CSRF", req, time.Since(start), 0, "")
return ck.Value, nil
}
}
logEvent("网络", "warn", "接口返回异常: 生成CSRF %s %s 耗时=%s msg=响应没有 cvl_csrf_token",
req.Method, requestPath(req), roundDuration(time.Since(start)))
return "", errors.New("CSRF 响应没有 cvl_csrf_token")
}
@@ -150,7 +160,7 @@ func (c *DouyuClient) BatchExchangeLimit(cookie, commodityID, csrf string) (int,
Limit string `json:"limit"`
} `json:"data"`
}
if err := c.postMultipart(batchLimitURL, cookie, csrf, map[string]string{
if err := c.postMultipart(batchLimitURL, cookie, csrf, "批量限制", map[string]string{
"manualID": manualID,
"commodityID": commodityID,
"rid": roomID,
@@ -171,7 +181,7 @@ func (c *DouyuClient) BatchExchangeLimit(cookie, commodityID, csrf string) (int,
// PreExchange 按抓包流程执行预兑换检查。
func (c *DouyuClient) PreExchange(cookie, commodityID, csrf string) error {
var result APIResponse
if err := c.postMultipart(preExchangeURL, cookie, csrf, map[string]string{
if err := c.postMultipart(preExchangeURL, cookie, csrf, "预兑换", map[string]string{
"manualID": manualID,
"rid": roomID,
"commodityID": commodityID,
@@ -196,7 +206,7 @@ func (c *DouyuClient) Exchange(cookie, commodityID, csrf string) (string, error)
CommodityTyp int `json:"commodityType"`
} `json:"data"`
}
if err := c.postMultipart(exchangeURL, cookie, csrf, map[string]string{
if err := c.postMultipart(exchangeURL, cookie, csrf, "正式兑换", map[string]string{
"manualID": manualID,
"commodityID": commodityID,
"num": "1",
@@ -224,7 +234,7 @@ func (c *DouyuClient) RoleName(cookie string) (string, error) {
} `json:"gameRole"`
} `json:"data"`
}
if err := c.getJSON(bindInfoURL, cookie, &result); err != nil {
if err := c.getJSON(bindInfoURL, cookie, "角色绑定", &result); err != nil {
return "", err
}
if result.Error != 0 {
@@ -234,17 +244,17 @@ func (c *DouyuClient) RoleName(cookie string) (string, error) {
}
// getJSON 发送 GET 请求并解析 JSON。
func (c *DouyuClient) getJSON(url, cookie string, out any) error {
func (c *DouyuClient) getJSON(url, cookie, label string, out any) error {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
c.setBrowserHeaders(req, cookie)
return c.doJSON(req, out)
return c.doJSON(req, out, label)
}
// postMultipart 发送 multipart/form-data 请求并解析 JSON。
func (c *DouyuClient) postMultipart(url, cookie, csrf string, fields map[string]string, out any) error {
func (c *DouyuClient) postMultipart(url, cookie, csrf, label string, fields map[string]string, out any) error {
var body bytes.Buffer
writer := multipart.NewWriter(&body)
for key, value := range fields {
@@ -262,30 +272,120 @@ func (c *DouyuClient) postMultipart(url, cookie, csrf string, fields map[string]
}
c.setBrowserHeaders(req, mergeCookie(cookie, "cvl_csrf_token", csrf))
req.Header.Set("Content-Type", writer.FormDataContentType())
return c.doJSON(req, out)
return c.doJSON(req, out, label)
}
// doJSON 执行请求、检查 HTTP 状态码并解析 JSON。
func (c *DouyuClient) doJSON(req *http.Request, out any) error {
func (c *DouyuClient) doJSON(req *http.Request, out any, label string) error {
start := time.Now()
resp, err := c.httpClient.Do(req)
if err != nil {
logNetworkError(label, req, time.Since(start), err)
return err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
logNetworkError(label, req, time.Since(start), err)
return err
}
if resp.StatusCode != http.StatusOK {
logNetworkHTTPError(label, req, resp.StatusCode, time.Since(start), body)
return fmt.Errorf("HTTP %d: %s", resp.StatusCode, trimForLog(string(body), 160))
}
if err := json.Unmarshal(body, out); err != nil {
logNetworkParseError(label, req, time.Since(start), body, err)
return fmt.Errorf("JSON 解析失败: %w, body=%s", err, trimForLog(string(body), 160))
}
if apiError, apiMsg, ok := extractAPIStatus(out); ok && apiError != 0 {
logNetworkAPIResult(label, req, time.Since(start), apiError, apiMsg)
} else if shouldLogNetworkSuccess(label) {
logNetworkSuccess(label, req, time.Since(start), 0, "")
}
return nil
}
func shouldLogNetworkSuccess(label string) bool {
return label != "服务时间"
}
func logNetworkSuccess(label string, req *http.Request, cost time.Duration, apiError int, apiMsg string) {
if !shouldLogNetworkSuccess(label) {
return
}
extra := ""
if apiMsg != "" || apiError != 0 {
extra = fmt.Sprintf(" apiError=%d msg=%s", apiError, trimForLog(apiMsg, 80))
}
logEvent("网络", "info", "请求完成: %s %s %s 耗时=%s%s", label, req.Method, requestPath(req), roundDuration(cost), extra)
}
func logNetworkAPIResult(label string, req *http.Request, cost time.Duration, apiError int, apiMsg string) {
logEvent("网络", "warn", "接口返回异常: %s %s %s 耗时=%s apiError=%d msg=%s",
label, req.Method, requestPath(req), roundDuration(cost), apiError, trimForLog(apiMsg, 120))
}
func logNetworkHTTPError(label string, req *http.Request, status int, cost time.Duration, body []byte) {
logEvent("网络", "error", "HTTP异常: %s %s %s 状态=%d 耗时=%s 响应=%s",
label, req.Method, requestPath(req), status, roundDuration(cost), trimForLog(string(body), 160))
}
func logNetworkParseError(label string, req *http.Request, cost time.Duration, body []byte, err error) {
logEvent("网络", "error", "响应解析失败: %s %s %s 耗时=%s 错误=%v 响应=%s",
label, req.Method, requestPath(req), roundDuration(cost), err, trimForLog(string(body), 160))
}
func logNetworkError(label string, req *http.Request, cost time.Duration, err error) {
logEvent("网络", "error", "请求失败: %s %s %s 耗时=%s 错误=%v",
label, req.Method, requestPath(req), roundDuration(cost), err)
}
func requestPath(req *http.Request) string {
if req == nil || req.URL == nil {
return "-"
}
return req.URL.Path
}
func roundDuration(d time.Duration) time.Duration {
return d.Round(time.Millisecond)
}
func extractAPIStatus(out any) (int, string, bool) {
if out == nil {
return 0, "", false
}
v := reflect.ValueOf(out)
if v.Kind() == reflect.Pointer {
if v.IsNil() {
return 0, "", false
}
v = v.Elem()
}
if !v.IsValid() {
return 0, "", false
}
if v.Type() == reflect.TypeOf(APIResponse{}) {
api := v.Interface().(APIResponse)
return api.Error, api.Msg, true
}
if v.Kind() != reflect.Struct {
return 0, "", false
}
if field := v.FieldByName("APIResponse"); field.IsValid() && field.CanInterface() {
if api, ok := field.Interface().(APIResponse); ok {
return api.Error, api.Msg, true
}
}
errorField := v.FieldByName("Error")
msgField := v.FieldByName("Msg")
if errorField.IsValid() && msgField.IsValid() && errorField.CanInt() && msgField.Kind() == reflect.String {
return int(errorField.Int()), msgField.String(), true
}
return 0, "", false
}
// setBrowserHeaders 设置接近浏览器抓包的通用请求头。
func (c *DouyuClient) setBrowserHeaders(req *http.Request, cookie string) {
req.Header.Set("Accept", "application/json, text/plain, */*")