Pārlūkot izejas kodu

gin logger重构,适配recovery与logger

jys 1 gadu atpakaļ
vecāks
revīzija
b25d4b17b7
2 mainītis faili ar 29 papildinājumiem un 7 dzēšanām
  1. 26 7
      gin_logger.go
  2. 3 0
      logger.go

+ 26 - 7
gin_logger.go

@@ -1,19 +1,38 @@
 package fslog
 
 import (
-	ginzap "github.com/gin-contrib/zap"
 	"github.com/gin-gonic/gin"
+	"runtime/debug"
+	"slices"
 	"time"
 )
 
 func GinLogger(skipPaths []string) gin.HandlerFunc {
-	return ginzap.GinzapWithConfig(log.logger.Desugar(), &ginzap.Config{
-		TimeFormat: time.RFC3339,
-		UTC:        true,
-		SkipPaths:  skipPaths,
-	})
+	return func(c *gin.Context) {
+		start := time.Now()
+		c.Next()
+
+		path := c.Request.URL.Path
+		if slices.Contains(skipPaths, path) {
+			return
+		}
+
+		end := time.Now()
+		Info(" %d | %d | %s | %s		 \"%s\"",
+			c.Writer.Status(),
+			end.Sub(start),
+			c.ClientIP(),
+			c.Request.Method,
+			path,
+		)
+	}
 }
 
 func GinRecovery() gin.HandlerFunc {
-	return ginzap.RecoveryWithZap(log.logger.Desugar(), true)
+	return func(c *gin.Context) {
+		err := recover()
+		if err != nil {
+			Error("%s", debug.Stack())
+		}
+	}
 }

+ 3 - 0
logger.go

@@ -33,6 +33,8 @@ type Logger struct {
 
 	// 所有的core
 	cores []zapcore.Core
+
+	writers []io.Writer
 }
 
 func New() *Logger {
@@ -153,6 +155,7 @@ func (l *Logger) NewFileOutput(opts ...FileOutputOpt) {
 func (l *Logger) NewOutput(writer io.Writer) {
 	cfg := zap.NewProductionEncoderConfig()
 	cfg.EncodeTime = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05")
+	l.writers = append(l.writers, writer)
 	l.AddCore(zapcore.NewCore(zapcore.NewJSONEncoder(cfg), zapcore.AddSync(writer), l.lv))
 }