golog

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2024 License: MIT Imports: 14 Imported by: 1

README

Log handler for the Go log/slog package

Overview

There are three handlers implemented in this package with a heavy focus on the development handler.

  1. Development - logging in development mode.
  2. Discard - all gets discarded, useful for integration testing where log lines can become noise.
  3. Production - a wrapper around slog's JSON handler with sensible defaults.

Usage - Development

This handler should only be used in development. It formats the log lines where the attribute keys are color coded.

It is encouraged to always set the default logger with slog.SetDefault(...) in order to not "depend" directly on this logger in your code base.

Example
devLogger := golog.NewDevelopment()
slog.SetDefault(devLogger)

slog.Info("this log will be pretty printed")
Output

Example code used to generate the output: https://golang.ir/play/p/Y0d-i5_SutP

Pasted_Image_21_04_2024__14_39

JSON Output

If the data passed in as a string or []byte is a valid JSON object, it will be automatically formatted, colorized, and its type marked as JSON.

image


Usage - Discard

All log lines will be discarded. Should be used for integration tests.

Example
discardLogger := golog.NewDiscard()
slog.SetDefault(discardLogger)

slog.Info("this log will be discarded")

Usage - Production

The production handler is just a wrapper for slog's JSON handler with a few sensible defaults:

  • Logs are output to stderr to align it to the POSIX standard
  • The default log level is slog.LevelInfo
  • slog's TimeKey is replaced in JSON to a property named t
  • slog's source is enabled and formatted to <file:line>, e.g. my_file.go:17
Example
prodLogger := golog.NewProduction()
slog.SetDefault(prodLogger)

slog.Info("this log will be output to stderr and formatted as JSON")

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewDevelopment

func NewDevelopment() *slog.Logger

func NewDiscard

func NewDiscard() *slog.Logger

func NewProduction

func NewProduction() *slog.Logger

Types

type DevHandler

type DevHandler struct {
	// contains filtered or unexported fields
}

func (*DevHandler) Enabled

func (p *DevHandler) Enabled(_ context.Context, level slog.Level) bool

func (*DevHandler) Handle

func (p *DevHandler) Handle(_ context.Context, r slog.Record) error

func (*DevHandler) WithAttrs

func (p *DevHandler) WithAttrs(attrs []slog.Attr) slog.Handler

func (*DevHandler) WithGroup

func (p *DevHandler) WithGroup(name string) slog.Handler

Jump to

Keyboard shortcuts

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