s99logger

package module
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 14 Imported by: 4 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

S99Logger

s99logger is a small structured Go logger built around typed events, human-readable console output, JSON logs, and optional localization.

Console logs are colored by default when writing to a terminal. JSON logs keep stable machine fields such as message_id and service.

Features

  • Typed app-owned events.
  • A log/slog handler for libraries that log through slog.
  • Console, JSON, and multi-sink in the core package; MinLevel gives each sink its own level.
  • Process-wide default logger with a one-call rotation.Configure setup.
  • Integrated i18n and log rotation.
  • Configurable console prefixes, service prefix, and colors.
  • Optional context as the last log argument for per-request language.
  • Translation coverage checks with Translator.Verify.

Install

go get github.com/smegg99/s99logger

Shape

Log calls are event-first. Context is optional and goes last when needed.

event := s99logger.NewEvent("server_starting", s99logger.Int("port", 8080))
logger.Info(event)
logger.Info(event, s99logger.LanguageContext("pl"))

For named app events, wrap NewEvent in a small function. For plural translations, use s99logger.NewPluralEvent.

Global logger

For apps that would rather not thread a *Logger through every call, the package keeps a process-wide default. rotation.Configure builds a console logger (plus a rotating JSON file sink when EnableFiles is set) and installs it; Close releases the file sink at shutdown.

if err := rotation.Configure(rotation.Config{
    Service:     "api",
    Level:       "info",
    EnableFiles: true,
    Directory:   "logs",
}); err != nil {
    panic(err)
}
defer s99logger.Close()

s99logger.Info(s99logger.NewEvent("server_starting", s99logger.Int("port", 8080)))

s99logger.Default() returns the installed logger when you need a *Logger value (e.g. to derive a request-scoped child with With), and SetDefault swaps it directly when you build sinks yourself. The default is usable before configuration: it writes to stderr at debug level.

ParseLevel reads a level name from config or flags: debug, info, warn (or warning) and error, trimmed and in any case. It reports false for anything else, so a typo is an error, not a silent info; rotation.Configure returns that error for an unknown Level. MinLevel(sink, level) wraps one sink so it drops records below its own level, for example a console at info beside a debug file.

Attributes that JSON cannot encode (a NaN, a channel) are written as text, and errors as their message, so the record is never lost. A rotating sink drops writes after Close.

Fatal logs at error level, releases the sinks so the record reaches disk, and exits with status 1. Deferred functions do not run, so keep it to startup failures the application cannot continue past.

Use examples/ for complete, runnable code.

Sinks

A Sink receives each resolved Record. Every sink here is safe for concurrent use, and the logger discards a sink's error.

Sink Writes
NewConsoleSink(w) one human-readable line per record; colored only when w is a terminal
NewJSONSink(w) one JSON object per line, time in UTC RFC 3339
MultiSink(sinks...) every record to each sink
MinLevel(sink, level) records at level or above to sink
rotation.New(opts) JSON to opts.Directory/opts.Filename, rotated daily at RotateAt and by MaxSizeMB; old files compressed with gzip unless Compression says none or zstd, and any other value is an error; writes after Close are dropped

rotation.Configure uses the same defaults as rotation.New.

slog

Logger.SlogHandler(id) adapts the logger for libraries that log through log/slog, such as Wails. Each slog record becomes event id with the slog message under detail; slog groups become dotted keys, and errors their text. Logger.Enabled(level) reports whether the logger passes a record at level to its sink; a MinLevel sink further down may still drop it.

slog.SetDefault(slog.New(s99logger.Default().SlogHandler("runtime")))

Examples

Run any example with go run ./examples/name.

Example Shows
minimal console logging with NewEvent
global process-wide default logger via rotation.Configure
basic TOML translations with go-i18n
pluralization plural messages selected by event count
mixedformats JSON, TOML, and YAML locale files together
localizedprefixes language-specific console prefixes/colors
consoleprefixes custom console prefixes, colors, and service style
jsonstdout newline-delimited JSON
multisink console and JSON from one log call
rotatingfile optional rotation package for daily JSON files
scopedattrs Logger.With and Options.MinLevel
verifytranslations Translator.Verify coverage check
customsink implementing Sink

License

MIT

Documentation

Index

Constants

View Source
const (
	ANSIRed    = "\x1b[31m"
	ANSIGreen  = "\x1b[32m"
	ANSIYellow = "\x1b[33m"

	ANSIBrightWhite = "\x1b[97m"
)

Variables

This section is empty.

Functions

func Close added in v1.0.1

func Close() error

Close releases the default Logger's closers; safe to call more than once.

func Debug added in v1.0.1

func Debug(event Event, ctx ...context.Context)

Debug logs event at debug level on the default Logger.

func Error added in v1.0.1

func Error(event Event, ctx ...context.Context)

Error logs event at error level on the default Logger.

func Fatal added in v1.1.0

func Fatal(event Event, ctx ...context.Context)

Fatal logs at error level, closes the sinks and exits with status 1 without running deferred functions.

func Info added in v1.0.1

func Info(event Event, ctx ...context.Context)

Info logs event at info level on the default Logger.

func LanguageContext

func LanguageContext(lang string) context.Context

LanguageContext returns a background context carrying lang.

func SetDefault added in v1.0.1

func SetDefault(l *Logger, sinkClosers ...io.Closer)

SetDefault installs l and its sinkClosers, closing the previous closers; a nil l is ignored.

func Warn added in v1.0.1

func Warn(event Event, ctx ...context.Context)

Warn logs event at warn level on the default Logger.

Types

type Attr

type Attr struct {
	Key   string
	Value any
}

Attr is one key/value pair on an event, emitted in the record and passed to translators as template data.

func Any

func Any(key string, value any) Attr

Any returns an attribute with an arbitrary value.

func Bool

func Bool(key string, value bool) Attr

Bool returns a boolean attribute.

func Duration

func Duration(key string, value time.Duration) Attr

Duration returns a duration attribute, rendered as text such as "1.5s" in logs and templates.

func Err

func Err(err error) Attr

Err returns an attribute carrying an error message under the "error" key.

func Int

func Int(key string, value int) Attr

Int returns an integer attribute.

func String

func String(key, value string) Attr

String returns a string attribute.

type ConsoleSink

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

ConsoleSink writes human-readable lines, colored on a terminal, with per-language level prefixes; safe for concurrent use.

func NewConsoleSink

func NewConsoleSink(w io.Writer) *ConsoleSink

NewConsoleSink returns a ConsoleSink writing to w, colored only when w is a terminal.

func (*ConsoleSink) WithColor

func (s *ConsoleSink) WithColor(on bool) *ConsoleSink

WithColor forces color on or off, overriding terminal detection.

func (*ConsoleSink) WithLevelColors

func (s *ConsoleSink) WithLevelColors(colors map[Level]string) *ConsoleSink

WithLevelColors sets default ANSI colors for levels; missing levels keep theirs.

func (*ConsoleSink) WithLevelPrefixes

func (s *ConsoleSink) WithLevelPrefixes(prefixes map[Level]string) *ConsoleSink

WithLevelPrefixes sets default console prefixes; missing levels keep theirs.

func (*ConsoleSink) WithLocalizedLevelColors

func (s *ConsoleSink) WithLocalizedLevelColors(lang string, colors map[Level]string) *ConsoleSink

WithLocalizedLevelColors sets ANSI colors for records in lang; missing levels keep theirs.

func (*ConsoleSink) WithLocalizedLevelPrefixes

func (s *ConsoleSink) WithLocalizedLevelPrefixes(lang string, prefixes map[Level]string) *ConsoleSink

WithLocalizedLevelPrefixes sets console prefixes for records in lang; missing levels keep theirs.

func (*ConsoleSink) WithServiceColor

func (s *ConsoleSink) WithServiceColor(color string) *ConsoleSink

WithServiceColor sets the service prefix's ANSI color; empty disables it.

func (*ConsoleSink) WithServicePrefixStyle

func (s *ConsoleSink) WithServicePrefixStyle(open, close string) *ConsoleSink

WithServicePrefixStyle sets the strings around the service prefix, [service] by default.

func (*ConsoleSink) Write

func (s *ConsoleSink) Write(_ context.Context, rec Record) error

Write renders rec as a single human-readable line.

type Event

type Event interface {
	// MessageID returns the stable identifier for this event.
	MessageID() MessageID
	// Attrs returns the structured attributes for this event.
	Attrs() []Attr
	// PluralCount returns the count used for plural translation selection.
	// The boolean is false for events that are not pluralized.
	PluralCount() (int, bool)
}

Event is a typed log event; NewEvent and NewPluralEvent cover the simple cases.

type JSONSink

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

JSONSink writes records as newline-delimited JSON; safe for concurrent use.

func NewJSONSink

func NewJSONSink(w io.Writer) *JSONSink

NewJSONSink returns a JSONSink writing to w.

func (*JSONSink) Write

func (s *JSONSink) Write(_ context.Context, rec Record) error

Write encodes rec as a single JSON object followed by a newline.

type Level

type Level int

Level is the severity of a log record.

const (
	LevelDebug Level = iota
	LevelInfo
	LevelWarn
	LevelError
)

func ParseLevel added in v1.0.1

func ParseLevel(name string) (level Level, ok bool)

ParseLevel reads debug, info, warn, warning or error in any case; ok is false otherwise.

func (Level) String

func (l Level) String() string

String returns the lowercase name of the level, used in log output.

type Logger

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

Logger emits typed events to a Sink, optionally translated; safe for concurrent use when its Sink is.

func Default added in v1.0.1

func Default() *Logger

Default returns the process-wide Logger; before SetDefault it writes to stderr at debug level.

func New

func New(sink Sink, opts Options) *Logger

New returns a Logger writing to sink; a nil sink discards records.

func With added in v1.0.1

func With(attrs ...Attr) *Logger

With is Default().With.

func (*Logger) Debug

func (l *Logger) Debug(event Event, ctx ...context.Context)

Debug logs an event at debug level.

func (*Logger) Enabled added in v1.3.0

func (l *Logger) Enabled(level Level) bool

Enabled reports whether a record at level reaches the sink.

func (*Logger) Error

func (l *Logger) Error(event Event, ctx ...context.Context)

Error logs an event at error level.

func (*Logger) Info

func (l *Logger) Info(event Event, ctx ...context.Context)

Info logs an event at info level.

func (*Logger) SlogHandler added in v1.3.0

func (l *Logger) SlogHandler(id MessageID) slog.Handler

SlogHandler returns a slog.Handler that logs each record as event id, the slog message under "detail".

func (*Logger) Warn

func (l *Logger) Warn(event Event, ctx ...context.Context)

Warn logs an event at warn level.

func (*Logger) With

func (l *Logger) With(attrs ...Attr) *Logger

With returns a child Logger that adds attrs to every record; the receiver is unchanged.

type MessageID

type MessageID string

MessageID is a stable, language-independent message id, emitted beside the text and used as the text when translation fails.

type NoPlural

type NoPlural struct{}

NoPlural lets an event struct satisfy Event without a PluralCount of its own.

func (NoPlural) PluralCount

func (NoPlural) PluralCount() (int, bool)

PluralCount reports that the event is not pluralized.

type Options

type Options struct {
	// Language is the default target language passed to the Translator. A call logged with
	// LanguageContext(lang) overrides it.
	Language string
	// Service is the service name attached to every record.
	Service string
	// MinLevel is the lowest level that is logged; lower levels are dropped
	// before any translation or sink work. The zero value (LevelDebug) logs
	// everything.
	MinLevel Level
	// Translator localizes events. If nil, messages are the message id.
	Translator Translator
	// Clock supplies the record timestamp. If nil, time.Now is used.
	Clock func() time.Time
}

Options configures a Logger; the zero value works, with time.Now and untranslated message ids.

type Record

type Record struct {
	Time      time.Time
	Level     Level
	Service   string
	Lang      string
	MessageID MessageID
	Message   string
	Attrs     []Attr
}

Record is a resolved entry: Message is the translated text or the id, MessageID always the id.

type SimpleEvent

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

SimpleEvent is an immutable Event for events that need no struct of their own.

func NewEvent

func NewEvent(id MessageID, attrs ...Attr) SimpleEvent

NewEvent returns a non-pluralized event with id and attrs.

func NewPluralEvent

func NewPluralEvent(id MessageID, count int, attrs ...Attr) SimpleEvent

NewPluralEvent returns an event whose count selects the plural form.

func (SimpleEvent) Attrs

func (e SimpleEvent) Attrs() []Attr

Attrs returns the structured attributes for this event.

func (SimpleEvent) MessageID

func (e SimpleEvent) MessageID() MessageID

MessageID returns the stable identifier for this event.

func (SimpleEvent) PluralCount

func (e SimpleEvent) PluralCount() (int, bool)

PluralCount returns the count used for plural translation selection.

func (SimpleEvent) With

func (e SimpleEvent) With(attrs ...Attr) SimpleEvent

With returns a copy of e with attrs appended.

type Sink

type Sink interface {
	Write(ctx context.Context, rec Record) error
}

Sink writes records somewhere; it must be safe for concurrent use, and the Logger discards its error.

func MinLevel added in v1.2.0

func MinLevel(sink Sink, min Level) Sink

MinLevel passes on records at min or above, so one logger at the lowest level can feed sinks at different levels.

func MultiSink

func MultiSink(sinks ...Sink) Sink

MultiSink writes each record to every sink and joins their errors.

type Translator

type Translator interface {
	Translate(ctx context.Context, lang string, event Event) (string, error)
}

Translator localizes an event for a language; on error the Logger falls back to the MessageID.

Directories

Path Synopsis
examples
basic command
consoleprefixes command
customsink command
global command
jsonstdout command
minimal command
mixedformats command
multisink command
pluralization command
rotatingfile command
scopedattrs command
Package i18n is the go-i18n adapter for s99logger, loading locale files from any fs.FS.
Package i18n is the go-i18n adapter for s99logger, loading locale files from any fs.FS.
Package rotation is a timberjack-backed, daily-rotated JSON file sink for s99logger.
Package rotation is a timberjack-backed, daily-rotated JSON file sink for s99logger.

Jump to

Keyboard shortcuts

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