Gzap
Alternative logging through zap for gin,use https://github.com/things-go/gin-contrib instead.
Install / Use
/learn @things-go/GzapREADME
gzap
gzap is a zap middleware for Gin
Usage
Installation
Use go get.
go get github.com/things-go/gzap
Then import the gazp package into your own code.
import "github.com/things-go/gzap"
Example
package main
import (
"errors"
"fmt"
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"github.com/things-go/gzap"
)
func main() {
r := gin.New()
logger, _ := zap.NewProduction()
// Add a ginzap middleware, which:
// - Logs all requests, like a combined access and error log.
// - Logs to stdout.
// - RFC3339 with UTC time format.
r.Use(gzap.Logger(logger,
gzap.WithCustomFields(
gzap.String("app", "example"),
func(c *gin.Context) zap.Field { return zap.String("custom field1", c.ClientIP()) },
func(c *gin.Context) zap.Field { return zap.String("custom field2", c.ClientIP()) },
),
gzap.WithSkipLogging(func(c *gin.Context) bool {
return c.Request.URL.Path == "/skiplogging"
}),
gzap.WithEnableBody(true),
))
// Logs all panic to error log
// - stack means whether output the stack info.
r.Use(gzap.Recovery(logger, true,
gzap.WithCustomFields(
gzap.Immutable("app", "example"),
func(c *gin.Context) zap.Field { return zap.String("custom field1", c.ClientIP()) },
func(c *gin.Context) zap.Field { return zap.String("custom field2", c.ClientIP()) },
),
))
// Example ping request.
r.GET("/ping", func(c *gin.Context) {
c.String(200, "pong "+fmt.Sprint(time.Now().Unix()))
})
// Example when panic happen.
r.GET("/panic", func(c *gin.Context) {
panic("An unexpected error happen!")
})
r.GET("/error", func(c *gin.Context) {
c.Error(errors.New("An error happen 1")) // nolint: errcheck
c.Error(errors.New("An error happen 2")) // nolint: errcheck
})
r.GET("/skiplogging", func(c *gin.Context) {
c.String(200, "i am skip logging, log should be not output")
})
// Listen and Server in 0.0.0.0:8080
r.Run(":8080")
}
License
This project is under MIT License. See the LICENSE file for the full license text.
Related Skills
node-connect
347.6kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
108.4kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
347.6kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
qqbot-media
347.6kQQBot 富媒体收发能力。使用 <qqmedia> 标签,系统根据文件扩展名自动识别类型(图片/语音/视频/文件)。
