slogger

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

README

slogger

codecov GoDoc

This is a helper package for log/slog to set up a *slog.Logger based on some defaults for text, JSON or output suitable for consumption by sd_journal_stream_fd (i.e., when your application is run as a systemd unit).

Usage

package main

import (
	"log/slog"
	"os"

	"github.com/andrewheberle/slogger"
)

func main() {
	// set up our logLevel variable to allow changing levels
	logLevel := new(slog.LevelVar)

	// create a logger with default settings
	logger, err := slogger.NewLogger(logLevel)
	if err != nil {
		panic(err)
	}

	// level is set to info by default
	logger.Debug("this will not be shown")
	logger.Info("this is an info level message", "withstring", "foo")

	// raise the log level to debug
	logLevel.Set(slog.LevelDebug)

	// output a debug message
	logger.Debug("this message is only shown if the log level is changed", "withnumber", 10)
}

Output Formats

By default the *slog.Logger is created with a handler as follows:

  1. If it is detected that the application is run by systemd (ie systemd is the parent process) logs are output as text to os.Stderr in the following format:

    <LEVEL> MESSAGE [KEY=VALUE KEY=VALUE ...]
    
  2. Otherwise the log is output using slog.NewTextHandler to os.Stderr

It is possible override or force a particular output format by passing slogger.WithLoggerType to slogger.NewLogger with one of the following options:

  • slogger.LoggerTypeAuto - chooses systemd or text output (default)
  • slogger.LoggerTypeDiscard - no output via slog.DiscardHandler
  • slogger.LoggerTypeJson - JSON output via slog.NewJSONHandler
  • slogger.LoggerTypeSystemd - custom text output for by sd_journal_stream_fd
  • slogger.LoggerTypeText - Text output using slog.NewTextHandler

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// This error is returned when an invalid [LoggerType] is provided to
	// [NewLogger] via [WithLoggerType]
	ErrUnhandledLoggerType = errors.New("unhandled logger type")
)

Functions

func NewLogger

func NewLogger(leveler slog.Leveler, opts ...LoggerOption) (*slog.Logger, error)

NewLogger creates a new slog.Logger with the provided slog.Leveler. By default the slog.Logger outputs to os.Stderr and will output using either slog.NewTextHandler or a SystemdHandler.

Types

type LoggerOption

type LoggerOption func(*logger)

LoggerOption allows passing options to NewLogger

func WithLoggerType

func WithLoggerType(lt LoggerType) LoggerOption

WithLoggerType allows overriding the default LoggerType of LoggerTypeAuto

func WithWriter

func WithWriter(w io.Writer) LoggerOption

WithWriter accepts an io.Writer in order to override the default of sending logs to os.Stderr

type LoggerType

type LoggerType string

The type of log handler to use

const (
	LoggerTypeAuto    LoggerType = "auto"
	LoggerTypeDiscard LoggerType = "discard"
	LoggerTypeJson    LoggerType = "json"
	LoggerTypeSystemd LoggerType = "systemd"
	LoggerTypeText    LoggerType = "text"
)

String constants for each log handler type

type LoggerTypeVar

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

This type satisfies the github.com/spf13/pflag.Value interface so LoggerType can be set via a command line flag

Example
package main

import (
	"log/slog"
	"os"

	"github.com/andrewheberle/slogger"
	"github.com/spf13/pflag"
)

func main() {
	lt := new(slogger.LoggerTypeVar)

	// set up a flagset
	f := pflag.NewFlagSet("example", pflag.ContinueOnError)
	f.Var(lt, "type", "Logger type (auto, discard, json, systemd or text)")

	// parse as though option provided was systemd
	f.Parse([]string{"--type", "systemd"})

	// set up our logLevel variable to allow changing levels
	logLevel := new(slog.LevelVar)

	// set up the logger based on the command line flag
	logger, err := slogger.NewLogger(logLevel,
		lt.LoggerTypeOption(),
		slogger.WithWriter(os.Stdout),
	)
	if err != nil {
		panic(err)
	}

	logger.Info("output using systemd handler")
}
Output:
<6> output using systemd handler

func (LoggerTypeVar) LoggerTypeOption added in v0.2.0

func (lt LoggerTypeVar) LoggerTypeOption() LoggerOption

Returns a LoggerOption suitable for passing to NewLogger

func (*LoggerTypeVar) Set

func (lt *LoggerTypeVar) Set(s string) error

Set is to satisfy the github.com/spf13/pflag.Value interface

func (*LoggerTypeVar) String

func (lt *LoggerTypeVar) String() string

Strig method for LoggerTypeVar

func (LoggerTypeVar) Type

func (lt LoggerTypeVar) Type() string

Type is to satisfy the github.com/spf13/pflag.Value interface

type SystemdHandler

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

A slog.Handler implementation to output text in a format suitable for sd_journal_stream_fd.

func NewSystemdHandler

func NewSystemdHandler(w io.Writer, opts *slog.HandlerOptions) *SystemdHandler

Creates a new SystemdHandler that can be used by slog.New

func (*SystemdHandler) Enabled

func (h *SystemdHandler) Enabled(_ context.Context, level slog.Level) bool

func (*SystemdHandler) Handle

func (h *SystemdHandler) Handle(_ context.Context, r slog.Record) error

func (*SystemdHandler) WithAttrs

func (h *SystemdHandler) WithAttrs(attrs []slog.Attr) slog.Handler

func (*SystemdHandler) WithGroup

func (h *SystemdHandler) WithGroup(name string) slog.Handler

Jump to

Keyboard shortcuts

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