gzap

package module
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2023 License: MIT Imports: 13 Imported by: 0

README

gzap

gzap is a zap middleware for Gin

GoDoc Go.Dev reference codecov Action Status Go Report Card Licence Tag

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.

Documentation

Overview

Package gzap provides log handling using zap package. Code structure based on ginrus package. see github.com/gin-contrib/zap

Index

Constants

View Source
const (
	FieldStatus = iota
	FieldMethod
	FieldPath
	FieldRoute
	FieldQuery
	FieldIP
	FieldUserAgent
	FieldLatency
	FieldRequestBody
	FieldResponseBody
)

Indices for renaming field.

Variables

This section is empty.

Functions

func Any added in v0.0.9

func Any(key string, value interface{}) func(c *gin.Context) zap.Field

Any custom immutable any field

func Float64 added in v0.0.9

func Float64(key string, value float64) func(c *gin.Context) zap.Field

Float64 custom immutable float32 field

func Int64 added in v0.0.9

func Int64(key string, value int64) func(c *gin.Context) zap.Field

Int64 custom immutable int64 field

func Logger

func Logger(logger *zap.Logger, opts ...Option) gin.HandlerFunc

Logger 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().

func Recovery

func Recovery(logger *zap.Logger, stack bool, opts ...Option) gin.HandlerFunc

Recovery 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.

func String added in v0.0.9

func String(key, value string) func(c *gin.Context) zap.Field

String custom immutable string field

func Uint64 added in v0.0.9

func Uint64(key string, value uint64) func(c *gin.Context) zap.Field

Uint64 custom immutable uint64 field

Types

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config logger/recover config

type Option

type Option func(c *Config)

Option logger/recover option

func WithBodyLimit added in v0.0.10

func WithBodyLimit(limit int) Option

WithBodyLimit optional custom request/response body limit. default: <=0, mean not limit

func WithCustomFields

func WithCustomFields(fields ...func(c *gin.Context) zap.Field) Option

WithCustomFields optional custom field

func WithEnableBody added in v0.0.10

func WithEnableBody(b bool) Option

WithEnableBody optional custom enable request/response body.

func WithFieldName added in v0.1.2

func WithFieldName(index int, name string) Option

WithFieldName optionally renames a log field. Example: `WithFieldName(gzap.FieldStatus, "httpStatusCode")`

func WithSkipLogging added in v0.0.6

func WithSkipLogging(f func(c *gin.Context) bool) Option

WithSkipLogging optional custom skip logging option.

func WithSkipRequestBody added in v0.1.4

func WithSkipRequestBody(f func(c *gin.Context) bool) Option

WithSkipRequestBody optional custom skip request body logging option.

func WithSkipResponseBody added in v0.1.4

func WithSkipResponseBody(f func(c *gin.Context) bool) Option

WithSkipResponseBody optional custom skip response body logging option.

func WithUseLoggerLevel added in v0.1.5

func WithUseLoggerLevel(f func(c *gin.Context) zapcore.Level) Option

WithUseLoggerLevel optional use logging level.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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