golib/gweb/ginlog/access_log.go
2023-10-17 17:21:14 +08:00

53 lines
1.3 KiB
Go

//
// access_log.go
// Copyright (C) 2022 tiglog <me@tiglog.com>
//
// Distributed under terms of the MIT license.
//
package ginlog
import (
"fmt"
"time"
"git.hexq.cn/tiglog/golib/logger"
"github.com/gin-gonic/gin"
)
func GinLogger(logfile string) gin.HandlerFunc {
log := logger.New(logger.NewProductionRotateBySize(logfile), logger.InfoLevel)
defer log.Sync()
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
raw := c.Request.URL.RawQuery
// Process request
c.Next()
// Stop timer
stop := time.Now()
latency := stop.Sub(start)
if latency > time.Minute {
latency = latency.Truncate(time.Second)
}
fields := []logger.Field{
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()),
}
if requestID := c.Writer.Header().Get("X-Request-Id"); requestID != "" {
fields = append(fields, logger.String("request_id", requestID))
}
log.Info("GIN request", fields...)
}
}