hlog

package
v1.33.0 Latest Latest
Warning

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

Go to latest
Published: May 4, 2024 License: MIT Imports: 9 Imported by: 410

Documentation

Overview

Package hlog provides a set of http.Handler helpers for zerolog.

Example (Handler)
//go:build !binary_log
// +build !binary_log

package main

import (
	"net/http"
	"os"
	"time"

	"net/http/httptest"

	"github.com/rs/zerolog"
	"github.com/rs/zerolog/hlog"
)

// fake alice to avoid dep
type middleware func(http.Handler) http.Handler
type alice struct {
	m []middleware
}

func (a alice) Append(m middleware) alice {
	a.m = append(a.m, m)
	return a
}
func (a alice) Then(h http.Handler) http.Handler {
	for i := range a.m {
		h = a.m[len(a.m)-1-i](h)
	}
	return h
}

func init() {
	zerolog.TimestampFunc = func() time.Time {
		return time.Date(2001, time.February, 3, 4, 5, 6, 7, time.UTC)
	}
}

func main() {
	log := zerolog.New(os.Stdout).With().
		Timestamp().
		Str("role", "my-service").
		Str("host", "local-hostname").
		Logger()

	c := alice{}

	// Install the logger handler with default output on the console
	c = c.Append(hlog.NewHandler(log))

	// Install some provided extra handlers to set some request's context fields.
	// Thanks to those handlers, all our logs will come with some pre-populated fields.
	c = c.Append(hlog.RemoteAddrHandler("ip"))
	c = c.Append(hlog.UserAgentHandler("user_agent"))
	c = c.Append(hlog.RefererHandler("referer"))
	//c = c.Append(hlog.RequestIDHandler("req_id", "Request-Id"))

	// Here is your final handler
	h := c.Then(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Get the logger from the request's context. You can safely assume it
		// will be always there: if the handler is removed, hlog.FromRequest
		// will return a no-op logger.
		hlog.FromRequest(r).Info().
			Str("user", "current user").
			Str("status", "ok").
			Msg("Something happened")
	}))
	http.Handle("/", h)

	h.ServeHTTP(httptest.NewRecorder(), &http.Request{})

}
Output:

{"level":"info","role":"my-service","host":"local-hostname","user":"current user","status":"ok","time":"2001-02-03T04:05:06Z","message":"Something happened"}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AccessHandler added in v1.0.1

func AccessHandler(f func(r *http.Request, status, size int, duration time.Duration)) func(next http.Handler) http.Handler

AccessHandler returns a handler that call f after each request.

func CtxWithID added in v1.21.0

func CtxWithID(ctx context.Context, id xid.ID) context.Context

CtxWithID adds the given xid.ID to the context

func CustomHeaderHandler added in v1.17.0

func CustomHeaderHandler(fieldKey, header string) func(next http.Handler) http.Handler

CustomHeaderHandler adds given header from request's header as a field to the context's logger using fieldKey as field key.

func EtagHandler added in v1.32.0

func EtagHandler(fieldKey string) func(next http.Handler) http.Handler

EtagHandler adds Etag header from response's header as a field to the context's logger using fieldKey as field key.

func FromRequest

func FromRequest(r *http.Request) *zerolog.Logger

FromRequest gets the logger in the request's context. This is a shortcut for log.Ctx(r.Context())

func HTTPVersionHandler added in v1.32.0

func HTTPVersionHandler(fieldKey string) func(next http.Handler) http.Handler

HTTPVersionHandler is similar to ProtoHandler, but it does not store the "HTTP/" prefix in the protocol name.

func HostHandler added in v1.32.0

func HostHandler(fieldKey string, trimPort ...bool) func(next http.Handler) http.Handler

HostHandler adds the request's host as a field to the context's logger using fieldKey as field key. If trimPort is set to true, then port is removed from the host.

func IDFromCtx added in v1.9.0

func IDFromCtx(ctx context.Context) (id xid.ID, ok bool)

IDFromCtx returns the unique id associated to the context if any.

func IDFromRequest

func IDFromRequest(r *http.Request) (id xid.ID, ok bool)

IDFromRequest returns the unique id associated to the request if any.

func MethodHandler

func MethodHandler(fieldKey string) func(next http.Handler) http.Handler

MethodHandler adds the request method as a field to the context's logger using fieldKey as field key.

func NewHandler

func NewHandler(log zerolog.Logger) func(http.Handler) http.Handler

NewHandler injects log into requests context.

func ProtoHandler added in v1.28.0

func ProtoHandler(fieldKey string) func(next http.Handler) http.Handler

ProtoHandler adds the requests protocol version as a field to the context logger using fieldKey as field Key.

func RefererHandler

func RefererHandler(fieldKey string) func(next http.Handler) http.Handler

RefererHandler adds the request's referer as a field to the context's logger using fieldKey as field key.

func RemoteAddrHandler

func RemoteAddrHandler(fieldKey string) func(next http.Handler) http.Handler

RemoteAddrHandler adds the request's remote address as a field to the context's logger using fieldKey as field key.

func RemoteIPHandler added in v1.32.0

func RemoteIPHandler(fieldKey string) func(next http.Handler) http.Handler

RemoteIPHandler is similar to RemoteAddrHandler, but logs only an IP, not a port.

func RequestHandler

func RequestHandler(fieldKey string) func(next http.Handler) http.Handler

RequestHandler adds the request method and URL as a field to the context's logger using fieldKey as field key.

func RequestIDHandler

func RequestIDHandler(fieldKey, headerName string) func(next http.Handler) http.Handler

RequestIDHandler returns a handler setting a unique id to the request which can be gathered using IDFromRequest(req). This generated id is added as a field to the logger using the passed fieldKey as field name. The id is also added as a response header if the headerName is not empty.

The generated id is a URL safe base64 encoded mongo object-id-like unique id. Mongo unique id generation algorithm has been selected as a trade-off between size and ease of use: UUID is less space efficient and snowflake requires machine configuration.

func ResponseHeaderHandler added in v1.32.0

func ResponseHeaderHandler(fieldKey, headerName string) func(next http.Handler) http.Handler

func URLHandler

func URLHandler(fieldKey string) func(next http.Handler) http.Handler

URLHandler adds the requested URL as a field to the context's logger using fieldKey as field key.

func UserAgentHandler

func UserAgentHandler(fieldKey string) func(next http.Handler) http.Handler

UserAgentHandler adds the request's user-agent as a field to the context's logger using fieldKey as field key.

Types

This section is empty.

Directories

Path Synopsis
internal
mutil
Package mutil contains various functions that are helpful when writing http middleware.
Package mutil contains various functions that are helpful when writing http middleware.

Jump to

Keyboard shortcuts

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