提交 9afc8689 authored 作者: mooncake's avatar mooncake

fix

上级 3350aa35
...@@ -18,7 +18,7 @@ func InitMysql(dbConfig *config.Database) (*sgorm.DB, error) { ...@@ -18,7 +18,7 @@ func InitMysql(dbConfig *config.Database) (*sgorm.DB, error) {
enableTrace = c.App.Middleware.Trace.Enable enableTrace = c.App.Middleware.Trace.Enable
}) })
slowThreshold := 100 * time.Millisecond slowThreshold := 0 * time.Millisecond
if dbConfig.Mysql.SlowThreshold != "" { if dbConfig.Mysql.SlowThreshold != "" {
st, e := time.ParseDuration(dbConfig.Mysql.SlowThreshold) st, e := time.ParseDuration(dbConfig.Mysql.SlowThreshold)
if e == nil && st > 0 { if e == nil && st > 0 {
......
...@@ -174,7 +174,6 @@ func getRequestBody(buf *bytes.Buffer, maxLen int) []byte { ...@@ -174,7 +174,6 @@ func getRequestBody(buf *bytes.Buffer, maxLen int) []byte {
return append(body[:maxLen-len(contentMark)], contentMark...) return append(body[:maxLen-len(contentMark)], contentMark...)
} }
// Logging print request and response info
func Logging(opts ...Option) gin.HandlerFunc { func Logging(opts ...Option) gin.HandlerFunc {
o := defaultOptions() o := defaultOptions()
o.apply(opts...) o.apply(opts...)
...@@ -182,13 +181,11 @@ func Logging(opts ...Option) gin.HandlerFunc { ...@@ -182,13 +181,11 @@ func Logging(opts ...Option) gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
start := time.Now() start := time.Now()
// ignore printing of the specified route
if _, ok := o.ignoreRoutes[c.Request.URL.Path]; ok { if _, ok := o.ignoreRoutes[c.Request.URL.Path]; ok {
c.Next() c.Next()
return return
} }
// print input information before processing
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
_, _ = buf.ReadFrom(c.Request.Body) _, _ = buf.ReadFrom(c.Request.Body)
...@@ -197,6 +194,7 @@ func Logging(opts ...Option) gin.HandlerFunc { ...@@ -197,6 +194,7 @@ func Logging(opts ...Option) gin.HandlerFunc {
zap.String("url", c.Request.URL.String()), zap.String("url", c.Request.URL.String()),
zap.Any("headers", c.Request.Header), zap.Any("headers", c.Request.Header),
} }
if c.Request.Method == http.MethodPost || c.Request.Method == http.MethodPut || c.Request.Method == http.MethodPatch || c.Request.Method == http.MethodDelete { if c.Request.Method == http.MethodPost || c.Request.Method == http.MethodPut || c.Request.Method == http.MethodPatch || c.Request.Method == http.MethodDelete {
fields = append(fields, fields = append(fields,
zap.Int("size", buf.Len()), zap.Int("size", buf.Len()),
...@@ -209,29 +207,29 @@ func Logging(opts ...Option) gin.HandlerFunc { ...@@ -209,29 +207,29 @@ func Logging(opts ...Option) gin.HandlerFunc {
c.Set(ctxutils.KeyAppName, o.appName) c.Set(ctxutils.KeyAppName, o.appName)
reqID := "" reqID := ""
if o.traceIDFrom == 1 { switch o.traceIDFrom {
case 1:
if v, isExist := c.Get(ctxutils.ContextTraceIDKey); isExist { if v, isExist := c.Get(ctxutils.ContextTraceIDKey); isExist {
if requestID, ok := v.(string); ok { if requestID, ok := v.(string); ok {
reqID = requestID reqID = requestID
fields = append(fields, zap.String(ctxutils.ContextTraceIDKey, reqID)) fields = append(fields, zap.String(ctxutils.ContextTraceIDKey, reqID))
} }
} }
} else if o.traceIDFrom == 2 { case 2:
reqID = c.Request.Header.Get(ctxutils.HeaderXRequestIDKey) reqID = c.Request.Header.Get(ctxutils.HeaderXRequestIDKey)
fields = append(fields, zap.String(ctxutils.ContextTraceIDKey, reqID)) fields = append(fields, zap.String(ctxutils.ContextTraceIDKey, reqID))
} }
o.log.Info("[middleware][logging]<<<<<<<<<req", fields...) o.log.Info("[middleware][logging]<<<<<<<<<req", fields...)
c.Request.Body = io.NopCloser(buf) c.Request.Body = io.NopCloser(buf)
//replace writer
newWriter := &bodyLogWriter{body: &bytes.Buffer{}, ResponseWriter: c.Writer} newWriter := &bodyLogWriter{body: &bytes.Buffer{}, ResponseWriter: c.Writer}
c.Writer = newWriter c.Writer = newWriter
ip := ips.GetClientIP(c) ip := ips.GetClientIP(c)
c.Set(ctxutils.KeyClientIP, ip) c.Set(ctxutils.KeyClientIP, ip)
// processing requests
c.Next() c.Next()
rspBodyMax := c.GetInt(ctxutils.KeyRspBodyMax) rspBodyMax := c.GetInt(ctxutils.KeyRspBodyMax)
...@@ -241,7 +239,6 @@ func Logging(opts ...Option) gin.HandlerFunc { ...@@ -241,7 +239,6 @@ func Logging(opts ...Option) gin.HandlerFunc {
isMedia = true isMedia = true
} }
//print return message after processing
fields = []zap.Field{ fields = []zap.Field{
zap.Int("code", c.Writer.Status()), zap.Int("code", c.Writer.Status()),
zap.String("cost", time.Since(start).String()), zap.String("cost", time.Since(start).String()),
...@@ -261,14 +258,17 @@ func Logging(opts ...Option) gin.HandlerFunc { ...@@ -261,14 +258,17 @@ func Logging(opts ...Option) gin.HandlerFunc {
fields = append(fields, zap.ByteString("body", getResponseBody(newWriter.body, o.maxLength))) fields = append(fields, zap.ByteString("body", getResponseBody(newWriter.body, o.maxLength)))
} }
} }
if reqID != "" { if reqID != "" {
fields = append(fields, zap.String(ctxutils.ContextTraceIDKey, reqID)) fields = append(fields, zap.String(ctxutils.ContextTraceIDKey, reqID))
} }
if time.Since(start) > time.Duration(200*time.Millisecond) { if time.Since(start) > time.Duration(200*time.Millisecond) {
o.log.Warn("[middleware][logging]>>>>>>>>>rsp", fields...) o.log.Warn("[middleware][logging]>>>>>>>>>rsp", fields...)
} else { } else {
o.log.Info("[middleware][logging]>>>>>>>>>rsp", fields...) o.log.Info("[middleware][logging]>>>>>>>>>rsp", fields...)
} }
} }
} }
......
...@@ -62,7 +62,7 @@ func New(h func(g *gin.Engine)) *gin.Engine { ...@@ -62,7 +62,7 @@ func New(h func(g *gin.Engine)) *gin.Engine {
r.Use(middleware.Logging( r.Use(middleware.Logging(
middleware.WithAppName(app.Name), middleware.WithAppName(app.Name),
middleware.WithMaxLen(8192), middleware.WithMaxLen(1024),
middleware.WithLog(logger.Get()), middleware.WithLog(logger.Get()),
middleware.WithTraceIDFromContext(), middleware.WithTraceIDFromContext(),
middleware.WithIgnoreRoutes("/metrics"), // ignore path middleware.WithIgnoreRoutes("/metrics"), // ignore path
...@@ -123,6 +123,10 @@ func New(h func(g *gin.Engine)) *gin.Engine { ...@@ -123,6 +123,10 @@ func New(h func(g *gin.Engine)) *gin.Engine {
h(r) h(r)
} }
r.GET("/health", handlerfunc.CheckHealth)
r.GET("/ping", handlerfunc.Ping)
r.GET("/codes", handlerfunc.ListCodes)
if config.IsNotProd() { if config.IsNotProd() {
contextPath := app.ContextPath contextPath := app.ContextPath
r.GET(contextPath+"/config", gin.WrapF(errcode.ShowConfig([]byte(config.Show())))) r.GET(contextPath+"/config", gin.WrapF(errcode.ShowConfig([]byte(config.Show()))))
...@@ -136,10 +140,6 @@ func New(h func(g *gin.Engine)) *gin.Engine { ...@@ -136,10 +140,6 @@ func New(h func(g *gin.Engine)) *gin.Engine {
} }
r.GET("/health", handlerfunc.CheckHealth)
r.GET("/ping", handlerfunc.Ping)
r.GET("/codes", handlerfunc.ListCodes)
global.G.Engine = r global.G.Engine = r
return r return r
......
...@@ -93,17 +93,17 @@ func gormConfig(o *options) *gorm.Config { ...@@ -93,17 +93,17 @@ func gormConfig(o *options) *gorm.Config {
} }
// print only slow queries // print only slow queries
if o.slowThreshold > 0 { // if o.slowThreshold > 0 {
config.Logger = logger.New( // config.Logger = logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // use the standard output asWriter // log.New(os.Stdout, "\r\n", log.LstdFlags), // use the standard output asWriter
logger.Config{ // logger.Config{
SlowThreshold: o.slowThreshold, // SlowThreshold: o.slowThreshold,
Colorful: true, // Colorful: true,
LogLevel: logger.Warn, // set the logging level, only above the specified level will output the slow query log // LogLevel: logger.Warn, // set the logging level, only above the specified level will output the slow query log
IgnoreRecordNotFoundError: true, // IgnoreRecordNotFoundError: true,
}, // },
) // )
} // }
return config return config
} }
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论