ginzap

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 15, 2022 License: MIT Imports: 11 Imported by: 511

README

zap

Run Tests Go Report Card GoDoc

Alternative logging through zap. Thanks for Pull Request from @yezooz

Usage

Start using it

Download and install it:

go get github.com/gin-contrib/zap

Import it in your code:

import "github.com/gin-contrib/zap"

Example

See the example.

package main

import (
  "fmt"
  "time"

  ginzap "github.com/gin-contrib/zap"
  "github.com/gin-gonic/gin"
  "go.uber.org/zap"
)

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(ginzap.Ginzap(logger, time.RFC3339, true))

  // Logs all panic to error log
  //   - stack means whether output the stack info.
  r.Use(ginzap.RecoveryWithZap(logger, true))

  // 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!")
  })

  // Listen and Server in 0.0.0.0:8080
  r.Run(":8080")
}

Skip logging

When you want to skip logging for specific path, please use GinzapWithConfig


r.Use(GinzapWithConfig(utcLogger, &Config{
  TimeFormat: time.RFC3339,
  UTC: true,
  SkipPaths: []string{"/no_log"},
}))

Log TraceID

If you want to log Open Telemetry TraceID, use GinzapWithConfig.

import "go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"

r.Use(otelgin.Middleware("demo")) // middleware to extract trace from http request

r.Use(ginzap.GinzapWithConfig(logger, &ginzap.Config{
  TimeFormat: time.RFC3339,
  UTC: true,
  TraceID: true,
}))

This will add the traceId field to log:

{
  "level": "info",
  "ts": 1658442963.805288,
  "caller": "ginzap/zap.go:82",
  "msg": "/test",
  "status": 200,
  "method": "GET",
  "path": "/test",
  "query": "",
  "ip": "127.0.0.1",
  "user-agent": "curl/7.29.0",
  "latency": 0.002036414,
  "time": "2022-07-21T22:36:03Z",
  "traceID": "285f31ec1dba4b79034c4415ad18e4ed"
}

Custom Zap fields

example for custom log request body and response request ID

func main() {
  r := gin.New()

  logger, _ := zap.NewProduction()

  r.Use(ginzap.GinzapWithConfig(logger, &ginzap.Config{
    UTC:        true,
    TimeFormat: time.RFC3339,
    Context: ginzap.Fn(func(c *gin.Context) (fields []zapcore.Field) {
      // log response ID
      if requestID := c.Writer.Header().Get("X-Request-Id"); requestID != "" {
        fields = append(fields, zap.String("request-id", requestID))
      }

      // log request body
      var body []byte
      var buf bytes.Buffer
      tee := io.TeeReader(c.Request.Body, &buf)
      body, _ = io.ReadAll(tee)
      c.Request.Body = io.NopCloser(&buf)
      fields = append(fields, zap.String("body", string(body)))

      return
    }),
  }))

  // Example ping request.
  r.GET("/ping", func(c *gin.Context) {
    c.Writer.Header().Add("X-Request-Id", "1234-5678-9012")
    c.String(200, "pong "+fmt.Sprint(time.Now().Unix()))
  })

  r.POST("/ping", func(c *gin.Context) {
    c.Writer.Header().Add("X-Request-Id", "9012-5678-1234")
    c.String(200, "pong "+fmt.Sprint(time.Now().Unix()))
  })

  // Listen and Server in 0.0.0.0:8080
  r.Run(":8080")
}

Documentation

Overview

Package ginzap provides log handling using zap package. Code structure based on ginrus package.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CustomRecoveryWithZap added in v0.1.0

func CustomRecoveryWithZap(logger *zap.Logger, stack bool, recovery gin.RecoveryFunc) gin.HandlerFunc

CustomRecoveryWithZap returns a gin.HandlerFunc (middleware) with a custom recovery handler that recovers from any panics and logs requests using uber-go/zap. All errors are logged using zap.Error(). stack means whether output the stack info. The stack info is easy to find where the error occurs but the stack info is too large.

func Ginzap

func Ginzap(logger *zap.Logger, timeFormat string, utc bool) gin.HandlerFunc

Ginzap returns a gin.HandlerFunc (middleware) that logs requests using uber-go/zap.

Requests with errors are logged using zap.Error(). Requests without errors are logged using zap.Info().

It receives:

  1. A time package format string (e.g. time.RFC3339).
  2. A boolean stating whether to use UTC time zone or local.

func GinzapWithConfig added in v0.0.2

func GinzapWithConfig(logger *zap.Logger, conf *Config) gin.HandlerFunc

GinzapWithConfig returns a gin.HandlerFunc using configs

func RecoveryWithZap

func RecoveryWithZap(logger *zap.Logger, stack bool) gin.HandlerFunc

RecoveryWithZap returns a gin.HandlerFunc (middleware) that recovers from any panics and logs requests using uber-go/zap. All errors are logged using zap.Error(). stack means whether output the stack info. The stack info is easy to find where the error occurs but the stack info is too large.

Types

type Config added in v0.0.2

type Config struct {
	TimeFormat string
	UTC        bool
	SkipPaths  []string
	TraceID    bool // optionally log Open Telemetry TraceID
	Context    Fn
}

Config is config setting for Ginzap

type Fn added in v0.1.0

type Fn func(c *gin.Context) []zapcore.Field

Directories

Path Synopsis
_example
example01 command
example02 command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL