2 Star 0 Fork 0

TeamsHub/backend-gopkg

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
log.go 1.46 KB
一键复制 编辑 原始数据 按行查看 历史
HCY 提交于 2024-05-10 13:07 . edit pkg
package hook
import (
"fmt"
"gitee.com/wuzheng0709/backend-gopkg/infrastructure/pkg/live/go-toolkit/http-client/core"
"time"
)
const (
SlowReqRecord = "SlowReqRecord"
ReqRecord = "ReqRecord"
ErrorReqRecord = "ErrorReqRecord"
// 默认慢请求时间
defaultSlowReqLong = 5 * time.Second
)
type LogHook struct {
// 超过SlowReqLong时间长度的请求,
// 将记录为慢请求。
// 如果为负数,代表不记录
// 默认为2秒
slowReqLong time.Duration
// 函数参数
// 记录信息;如日志记录
record func(tag, msg string)
}
func (log *LogHook) BeforeRequest(req core.Request, client core.Client) error {
return nil
}
func (log *LogHook) AfterRequest(cErr error, req core.Request, client core.Client) {
if nil != cErr {
if nil != log.record {
log.record(ErrorReqRecord, fmt.Sprintf("query:: %s error:: %v ", req.String(), cErr))
}
} else {
if nil != log.record {
resp := req.Response()
reqInfo := fmt.Sprintf(" http query:: %s status:%d \n response:%s \n ts:(%v) \n",
req.String(),
resp.StatusCode,
resp.ToString(),
req.ReqLongTime())
if log.slowReqLong > 0 && req.ReqLongTime() >= log.slowReqLong {
log.record(SlowReqRecord, reqInfo)
}
log.record(ReqRecord, reqInfo)
}
}
}
func NewLogHook(slowReqLong time.Duration, record func(tag, msg string)) *LogHook {
if slowReqLong == 0 {
slowReqLong = defaultSlowReqLong
}
return &LogHook{
slowReqLong: slowReqLong,
record: record,
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wuzheng0709/backend-gopkg.git
git@gitee.com:wuzheng0709/backend-gopkg.git
wuzheng0709
backend-gopkg
backend-gopkg
v1.4.14

搜索帮助