ginlogr

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2019 License: MIT Imports: 11 Imported by: 2

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.RecoveryWithLogr(logger, time.RFC3339, true, 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")
}

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 bool) 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 RecoveryWithLogr

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

RecoveryWithlogr returns a gin.HandlerFunc (middleware) that recovers from any panics and logs requests 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.

Types

This section is empty.

Jump to

Keyboard shortcuts

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