Skip to content

Commit

Permalink
custom log trace
Browse files Browse the repository at this point in the history
  • Loading branch information
flyhope committed Oct 20, 2020
1 parent cc2b437 commit 7ccd21a
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 24 deletions.
22 changes: 18 additions & 4 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package yar

import (
"errors"
"github.com/flyhope/go-yar/comm"
"github.com/flyhope/go-yar/pack"
"github.com/sirupsen/logrus"
"io/ioutil"
Expand All @@ -15,6 +14,7 @@ type Client struct {
Response *pack.Response
Http *http.Request
HttpClient *http.Client
LogTrace LogTrace
}

// 初始化一个客户端
Expand Down Expand Up @@ -57,10 +57,24 @@ func (c *Client) Send() error {
c.Http.Body = ioutil.NopCloser(buffer)
c.Http.Header.Set("Content-Type", packHandler.ContentType())

comm.Log.WithFields(logrus.Fields{"YAR": "Request"}).Debug(string(data))
Log.WithFields(logrus.Fields{"YAR": "Request"}).Debug(string(data))

// 发送请求
timeStart := time.Now()
resp, err := c.HttpClient.Do(c.Http)

// 通过接口记录跟踪日志
if c.LogTrace != nil {
timeEnd := time.Now()
traceData := &LogTraceData{
TimeStart: timeStart,
TimeEnd: timeEnd,
Request: c.Http,
Err: err,
}
c.LogTrace.Trace(traceData)
}

if err != nil {
return err
}
Expand All @@ -77,10 +91,10 @@ func (c *Client) Send() error {
err = packHandler.Decode(bodyContent, c.Response)

if c.Response.Except != nil {
comm.Log.WithFields(logrus.Fields{"YAR": "Except"}).Debug(c.Response.Except)
Log.WithFields(logrus.Fields{"YAR": "Except"}).Debug(c.Response.Except)
}

comm.Log.WithFields(logrus.Fields{"YAR": "BodyContent"}).Debug(string(bodyContent))
Log.WithFields(logrus.Fields{"YAR": "BodyContent"}).Debug(string(bodyContent))

if err != nil {
return err
Expand Down
18 changes: 0 additions & 18 deletions comm/log.go

This file was deleted.

32 changes: 32 additions & 0 deletions log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package yar

import (
"github.com/sirupsen/logrus"
"net/http"
"time"
)

type LogTraceData struct {
TimeStart time.Time
TimeEnd time.Time
Request *http.Request
Err error
}

type LogTrace interface {
Trace(data *LogTraceData)
}

var Log = logrus.New()

func init() {
// 配置日志
var formatter logrus.Formatter
formatter = &logrus.TextFormatter{
ForceColors: true,
FullTimestamp: true,
TimestampFormat: "2006-01-02 15:04:05",
}
Log.SetFormatter(formatter)
Log.SetLevel(logrus.WarnLevel)
}
3 changes: 1 addition & 2 deletions set.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package yar

import (
"github.com/flyhope/go-yar/comm"
"github.com/sirupsen/logrus"
)

Expand All @@ -18,5 +17,5 @@ const (

// 设置日志输出级别
func SetLevel(level Level) {
comm.Log.SetLevel(logrus.Level(level))
Log.SetLevel(logrus.Level(level))
}

0 comments on commit 7ccd21a

Please sign in to comment.