zerologgin

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2023 License: MIT Imports: 7 Imported by: 0

README

zerolog-gin

Unittest status badge Coverage status badge Linter status badge Go Report Card Go Reference license

Zerolog logger for gin

Installation

go get github.com/hochfrequenz/zerolog-gin

Usage

package main

import (
    "bytes"
    "fmt"
    "github.com/gin-gonic/gin"
    zerologgin "github.com/Hochfrequenz/zerolog-gin"
    "github.com/rs/zerolog"
    "io"
    "net/http"
    "os"
)

func main() {
    // logger to use with gin
    logger := zerolog.New(os.Stdout).With().Timestamp().Logger()

    // Create an instance of gin router
    r := gin.New()
    r.SetTrustedProxies([]string{"::1"})

    // Add zerolog-gin as a middleware
    r.Use(zerologgin.LoggerWithOptions(&zerologgin.Options{Name: "server", Logger: &logger}))

    r.GET("/", func(c *gin.Context) {
        c.String(http.StatusOK, "hello, zerolog-gin example")
    })

    r.GET("/ping", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"message": "pong"})
    })

    r.POST("/echo", func(c *gin.Context) {
        body, err := io.ReadAll(c.Request.Body)
        c.Request.Body = io.NopCloser(bytes.NewReader(body))
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "undefined"})
        } else {
            c.String(http.StatusOK, string(body))
        }
    })

    if err := r.Run(":8080"); err != nil {
        fmt.Println(err.Error())
    }
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	NameFieldName      = "name"
	HostnameFieldName  = "hostname"
	ClientIPFieldName  = "client_ip"
	UserAgentFieldName = "user_agent"
	TimestampFieldName = zerolog.TimestampFieldName
	DurationFieldName  = "elapsed"
	MethodFieldName    = "method"
	PathFieldName      = "path"
	PayloadFieldName   = "payload"
	RefererFieldName   = "referer"

	DataLengthFieldName = "data_length"
	BodyFieldName       = "body"
)

Functions

func Logger

func Logger() gin.HandlerFunc

Logger is a gin middleware which use zerolog

func LoggerWithOptions

func LoggerWithOptions(opt *Options) gin.HandlerFunc

LoggerWithOptions is a gin middleware which use zerolog

Types

type Options

type Options struct {
	//
	Name string

	// Custom logger
	Logger *zerolog.Logger

	// FieldsOrder defines the order of fields in output.
	FieldsOrder []string

	// FieldsExclude defines contextual fields to not display in output.
	FieldsExclude []string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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