加日志
This commit is contained in:
parent
eb11666b46
commit
66fd805c1a
@ -8,12 +8,15 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"hospital-admin-api/config"
|
||||
"hospital-admin-api/global"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
@ -79,28 +82,34 @@ func (c *Client) postForm(path string, form url.Values, out interface{}) error {
|
||||
|
||||
resp, err := c.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
c.logUpstreamError(path, form, "request_error", err.Error())
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
c.logUpstreamError(path, form, "read_body_error", err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
c.logUpstreamResponse(path, form, resp.StatusCode, string(respBody))
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("ca v2 request failed: http %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var envelope responseEnvelope
|
||||
if err := json.Unmarshal(respBody, &envelope); err != nil {
|
||||
c.logUpstreamError(path, form, "unmarshal_error", err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
if envelope.ResultCode != 0 {
|
||||
if envelope.ResultMsg != "" {
|
||||
c.logUpstreamError(path, form, "upstream_business_error", envelope.ResultMsg)
|
||||
return errors.New(envelope.ResultMsg)
|
||||
}
|
||||
return fmt.Errorf("ca v2 request failed with code %d", envelope.ResultCode)
|
||||
@ -172,3 +181,30 @@ func setValue(form url.Values, key, value string) {
|
||||
}
|
||||
form.Set(key, value)
|
||||
}
|
||||
|
||||
func (c *Client) logUpstreamResponse(path string, form url.Values, statusCode int, body string) {
|
||||
if global.Logger == nil {
|
||||
return
|
||||
}
|
||||
|
||||
global.Logger.WithFields(logrus.Fields{
|
||||
"module": "ca_v2",
|
||||
"upstream_path": path,
|
||||
"upstream_status": statusCode,
|
||||
"request_form": form.Encode(),
|
||||
"response_body": body,
|
||||
}).Info("ca v2 upstream response")
|
||||
}
|
||||
|
||||
func (c *Client) logUpstreamError(path string, form url.Values, stage string, message string) {
|
||||
if global.Logger == nil {
|
||||
return
|
||||
}
|
||||
|
||||
global.Logger.WithFields(logrus.Fields{
|
||||
"module": "ca_v2",
|
||||
"stage": stage,
|
||||
"upstream_path": path,
|
||||
"request_form": form.Encode(),
|
||||
}).Error(message)
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user