fingerscrossed

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2023 License: MIT Imports: 5 Imported by: 0

README

slog-fingerscrossed 🤞

godoc

Golang slog.Handler with fingers-crossed strategy.

Inspired by PHP Monolog.

What is the fingers-crossed strategy?

It takes your logs no matter their level and buffers them.

It then flushes them only if an error is logged.

This allows logging debug information when an error happens, while not polluting your logs when everything works fine.

See the example for more information.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithThresholdLevel

func WithThresholdLevel(level slog.Level) option

WithThresholdLevel modifies the level at which the handler will flush its logs and stop buffering them. Default is slog.LevelError

Types

type Handler

type Handler interface {
	slog.Handler
	FlushLogs(minimumLevel slog.Level) error
}
Example
package main

import (
	fingerscrossed "github.com/hectorj/slog-fingerscrossed"
	"log/slog"
	"os"
)

func main() {
	// 2 scenarios: with and without error logs

	// Scenario 1: without error
	{
		baseHandler := slog.NewJSONHandler(os.Stderr, nil)
		fingerscrossedHandler := fingerscrossed.NewHandler(baseHandler)

		logger := slog.New(fingerscrossedHandler)

		logger.Debug("debug msg") // <-- no log output
		logger.Info("info msg")   // <-- no log output
		logger.Warn("warn msg")   // <-- no log output

		_ = fingerscrossedHandler.FlushLogs(slog.LevelInfo) // <-- outputs "info msg" and "warn msg" logs, but not "debug msg"
	}
	// Scenario 2: with error
	{
		baseHandler := slog.NewJSONHandler(os.Stderr, nil)
		fingerscrossedHandler := fingerscrossed.NewHandler(baseHandler)

		logger := slog.New(fingerscrossedHandler)

		logger.Debug("debug msg") // <-- no log output
		logger.Info("info msg")   // <-- no log output
		logger.Error("error msg") // <-- outputs "debug msg", "info msg", and "error msg" logs
		logger.Warn("warn msg")   // <-- outputs "warn msg" log

		_ = fingerscrossedHandler.FlushLogs(slog.LevelInfo) // <-- everything is already flushed, nothing happens
	}
}
Output:

func NewHandler

func NewHandler(wrapping slog.Handler, options ...option) Handler

Jump to

Keyboard shortcuts

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