ginlogr

package module
v2.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2025 License: MIT Imports: 11 Imported by: 0

README

ginlogr

Alternative gin-gonic middleware logging through logr.

The Majority of the code used here was lifted from ginzap.

Usage

Start using it

Download and install it:

$ go get github.com/alron/ginlogr
$

Import it in your code:

import "github.com/alron/ginlogr"

Example

package main

import (
    "fmt"
    "time"

    "github.com/gin-gonic/gin"
    "github.com/go-logr/zapr"
    "go.uber.org/zap"
    "github.com/alron/ginlogr"
)

func main() {
    r := gin.New()
    // We use zap and zapr here, but you can really use any of the loggers
    // supported by logr
    zl, _ := zap.NewProduction()
    logger := zapr.NewLogger(zl)

    // Add a ginlogr middleware, which:
    //   - Logs all requests, like a combined access and error log.
    //   - Logs to stdout.
    //   - RFC3339 with UTC time format.
    r.Use(ginlogr.Ginlogr(logger, time.RFC3339, true))

    // Logs all panic to error log
    //   - RFC3389 with UTC time format.
    //   - stack means whether output the stack info.
    r.Use(ginlogr.PanicLogr(logger, time.RFC3339, true, true, "x-request-id"))

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

Documentation

Overview

Package ginlogr provides log handling using logr package. Code structure based on ginrus package.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Ginlogr

func Ginlogr(logger logr.Logger, timeFormat string, utc, addToReqContext bool, withHeaders []string) gin.HandlerFunc

Ginlogr returns a gin.HandlerFunc (middleware) that logs requests using github.com/go-logr/logr.

Requests with errors are logged using logr.Error(). Requests without errors are logged using logr.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 PanicLogr

func PanicLogr(logger logr.Logger, timeFormat string, utc, stack bool, requestIdCtxKey string) gin.HandlerFunc

PanicLogr returns a gin.HandlerFunc (middleware) that logs requests and panics using uber-go/logr. All errors are logged using logr.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. This does not consume the panic, the panic is passed up

Types

This section is empty.

Jump to

Keyboard shortcuts

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