zerologger

package module
v1.5.2 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2021 License: MIT Imports: 12 Imported by: 0

README

Zerologger: logger middleware for Echo

reference report tests coverage

A simple package to use Zerolog as the Logger for Echo.

⚙️ Installation

go get -u czechia.dev/zerologger

📝 Format

Zerologger was inspired by the default Logger middleware in Fiber, replacing the string buffers and templates with Zerolog Events. The key differences are:

  • uses a slice of strings to define the log format
  • no color output options, zerolog does not support it

The recommended method is to pass in a slice using the provided constants:

Format: []string{
	zerologger.TagTime,
	zerologger.TagStatus,
	zerologger.TagLatency,
	zerologger.TagMethod,
	zerologger.TagPath,
}

Some constants have a trailing semicolon. These can be used to extract data from the current context, so that header:X-Test-Header will add "X-Test-Header": "test-value" to the log.

👀 Example

package main

import (
	"net/http"

	"czechia.dev/zerologger"
	"github.com/labstack/echo/v4"
)

func main() {
	e := echo.New()
	e.Use(zerologger.New(zerologger.Config{
		Format: []string{
			zerologger.TagTime,
			zerologger.TagStatus,
			zerologger.TagLatency,
			zerologger.TagMethod,
			zerologger.TagPath,
		},
	}))

	e.GET("/", func(c echo.Context) error {
		return c.String(http.StatusOK, "Hello, World! 👋")
	})

	e.Start(":8080")
}

⏱ Benchmarks

Zerologger is faster than the default Echo logger and with fewer allocations. Zerologger significantly reduces the latency when logging with Timestamps. It also has the advantage that Zerologger can be configured to produce either structured logs or pretty logs without editing the custom Format string.

Below are some benchmarks with:

  1. Minimal format
  2. Default format, no time
  3. Default format
  4. All tags enabled, no time
  5. All tags enabled

Despite some 'large' differences in the results between the two loggers, they both perform great and neither will have a noticable impact on your services (your business logic will be orders of magnitude more taxing than the actual logging).

Results
goos: darwin
goarch: amd64
pkg: czechia.dev/zerologger
cpu: Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz

Benchmark_Zerologger/Minimal-8           2927076               389.5 ns/op            91 B/op          2 allocs/op
Benchmark_Echo/Minimal-8                 2093095               561.6 ns/op           153 B/op          3 allocs/op

Benchmark_Zerologger/DefaultNoTime-8     1863060               621.1 ns/op           107 B/op          2 allocs/op
Benchmark_Echo/DefaultNoTime-8           2074165               581.6 ns/op           157 B/op          4 allocs/op

Benchmark_Zerologger/Default-8           1765065               665.6 ns/op           109 B/op          2 allocs/op
Benchmark_Echo/Default-8                 1250151               982.3 ns/op           182 B/op          5 allocs/op

Benchmark_Zerologger/MaximumNoTime-8      874166              1378   ns/op           206 B/op          7 allocs/op
Benchmark_Echo/MaximumNoTime-8            809390              1437   ns/op           266 B/op          9 allocs/op

Benchmark_Zerologger/Maximum-8            768734              1413   ns/op           186 B/op          7 allocs/op
Benchmark_Echo/Maximum-8                  564432              1845   ns/op           284 B/op         10 allocs/op

PASS
ok      czechia.dev/zerologger  14.658s

Documentation

Index

Constants

View Source
const (
	TagPid               = "pid"
	TagTime              = "time"
	TagReferer           = "referer"
	TagProtocol          = "protocol"
	TagID                = "id"
	TagIP                = "ip"
	TagIPs               = "ips"
	TagHost              = "host"
	TagMethod            = "method"
	TagPath              = "path"
	TagURL               = "url"
	TagUA                = "ua"
	TagLatency           = "latency"
	TagStatus            = "status"
	TagResBody           = "resBody"
	TagQueryStringParams = "queryParams"
	TagBody              = "body"
	TagBytesSent         = "bytesSent"
	TagBytesReceived     = "bytesReceived"
	TagRoute             = "route"
	TagError             = "error"
	TagHeader            = "header:"
	TagLocals            = "locals:"
	TagQuery             = "query:"
	TagForm              = "form:"
	TagCookie            = "cookie:"
)

Logger variables

Variables

This section is empty.

Functions

func Initialize added in v1.3.0

func Initialize(level string, pretty bool) error

Initialize is a convenience function to configure Zerolog with some useful defaults.

func New

func New(config ...Config) echo.MiddlewareFunc

New creates a new zerolog middleware for Echo.

The default Logger middleware from Echo uses buffers and templates and writes directly to os.Stderr. This strips out all of that and sends the log directly to Zerolog.

Types

type Config

type Config struct {

	// Skipper defines a function to skip this middleware when returned true.
	// This field is used only by Echo.
	//
	// Optional. Default: nil
	Skipper middleware.Skipper

	// Format defines the logging tags
	//
	// Optional. Default: []string{TagTime, TagStatus, TagLatency, TagMethod, TagPath}
	Format []string

	// TimeZone can be specified, such as "UTC" and "America/New_York" and "Asia/Chongqing", etc
	//
	// Optional. Default: "Local"
	TimeZone string

	// TimeFormat https://programming.guide/go/format-parse-string-time-date-example.html
	//
	// Optional. Default: time.RFC3339
	TimeFormat string

	// TimeInterval is the delay before the timestamp is updated
	//
	// Optional. Default: 500 * time.Millisecond, Minimum: 500 * time.Millisecond
	TimeInterval time.Duration

	// Output is an io.Writer where logs can be written. Zerologger will copy
	// the global Logger if Output is not set. Typically used in tests.
	//
	// Optional. Default: nil
	Output io.Writer

	// PrettyLatency prints the latency as a string instead of a number.
	//
	// Optional. Default: false
	PrettyLatency bool
	// contains filtered or unexported fields
}

Config defines the Zerologger config for the middleware.

Jump to

Keyboard shortcuts

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