golib/gweb/ginlog/access_log.go

54 lines
1.3 KiB
Go
Raw Normal View History

2023-06-15 21:22:51 +08:00
//
// access_log.go
// Copyright (C) 2022 tiglog <me@tiglog.com>
//
// Distributed under terms of the MIT license.
//
2023-10-17 17:21:14 +08:00
package ginlog
2023-06-15 21:22:51 +08:00
import (
2023-08-12 20:03:19 +08:00
"fmt"
2023-06-15 21:22:51 +08:00
"time"
2023-06-15 21:38:12 +08:00
"git.hexq.cn/tiglog/golib/logger"
2023-08-12 20:03:19 +08:00
"github.com/gin-gonic/gin"
2023-06-15 21:22:51 +08:00
)
2023-08-12 20:03:19 +08:00
func GinLogger(logfile string) gin.HandlerFunc {
2023-10-31 09:59:03 +08:00
log := logger.New(logger.NewRotateBySize(logfile), logger.InfoLevel)
2023-08-12 20:03:19 +08:00
defer log.Sync()
2023-06-15 21:22:51 +08:00
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
raw := c.Request.URL.RawQuery
2023-08-12 20:03:19 +08:00
// Process request
2023-06-15 21:22:51 +08:00
c.Next()
2023-08-12 20:03:19 +08:00
// Stop timer
stop := time.Now()
latency := stop.Sub(start)
if latency > time.Minute {
latency = latency.Truncate(time.Second)
2023-06-15 21:22:51 +08:00
}
2023-10-17 17:21:14 +08:00
fields := []logger.Field{
2023-08-12 20:03:19 +08:00
logger.String("start", start.Format(time.RFC3339)),
logger.Int("status", c.Writer.Status()),
logger.String("latency", fmt.Sprintf("%s", latency)),
logger.String("method", c.Request.Method),
logger.String("path", path),
logger.String("query", raw),
logger.String("clientIP", c.ClientIP()),
logger.String("userAgent", c.Request.UserAgent()),
logger.String("error", c.Errors.ByType(gin.ErrorTypePrivate).String()),
2023-10-17 17:21:14 +08:00
}
2023-10-17 18:26:08 +08:00
if requestID := c.Writer.Header().Get("X-Request-Id"); requestID != "" {
// logger.With(logger.String("reqId", requestID))
2023-10-17 21:05:30 +08:00
fields = append([]logger.Field{logger.String("reqId", requestID)}, fields...)
2023-10-17 18:26:08 +08:00
}
2023-10-17 17:21:14 +08:00
log.Info("GIN request", fields...)
2023-06-15 21:22:51 +08:00
}
}