logging

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 16 Imported by: 6 modules, 6 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

go-backend-logging

Structured logging for Go services on top of the standard library's log/slog. Part of the go-backend-* family.

  • Console: one readable line per entry, 2026-01-02T10:00:00.000+11:00 [my-app] [info] message key=value, coloured when stdout is a terminal.
  • Files: JSON lines, rotated daily as <date>_<app>_<host>_<level>.log, with a stable symlink <app>_<level>.log pointing at today's file. There are two files: verbose gets everything at or above the minimum level, error gets errors only. Old files can be gzipped and pruned.
  • Levels: error, warn, info, debug and an extra verbose level below debug.
  • Context: attributes stored on a context.Context (request ID, correlation ID, user, ...) are added to every entry logged with that context. WithScope starts a per-request bag, so attributes added deeper in the chain (the user, set by auth middleware) also reach entries logged further out, such as the access log.
  • MongoDB: every entry goes to the logs collection, written in the background in batches. Signed-in requests and Event calls also become rows in the dau time-series collection for daily active users. Both expire after retentionDays (default 90).
  • Redaction: keys such as password, authorization, cookie, refreshToken, secret (see DefaultRedactKeys, plus redactKeys from config) are replaced with [redacted] in every output, including nested groups.

Install

go get github.com/ahmedbaig/go-backend-logging

Usage

cfg := logging.DefaultConfig()
log, err := logging.New(cfg, "my-app")
if err != nil {
	panic(err)
}
defer log.Close()

log.Info("server started", "port", 8080)
log.Verbose("cache warm", "entries", 1200)
log.Error("payment failed", logging.Err(err))

ctx = logging.WithAttrs(ctx, slog.String("requestId", id))
log.InfoContext(ctx, "handled")

log, err = logging.New(cfg, "my-app", logging.WithMeta("production", "1.4.0"))
logging.Event(ctx, log.Logger, "weather.viewed", slog.String("city", "Sydney"))

Logger embeds *slog.Logger, so it can be passed anywhere a *slog.Logger is expected (log.Logger).

Config

Loaded as JSON, typically with go-backend-config under the name <app>-logger.

Key Default
logDirectory /app/var/logs where log files go
minimumLogLevel verbose error, warn, info, debug, verbose
logToFile true write the JSON files
logToConsole true write console lines to stdout
zippedArchive false gzip yesterday's files after rotation
maxFiles 14 files kept per level (0 = keep all)
consoleColor auto force colour on or off
logToMongo false write every entry to MongoDB
mongo.uri, mongo.database connection; collections logs and dau are created with indexes and TTL on start
mongo.retentionDays 90 TTL for both collections
mongo.batchSize, mongo.bufferSize, mongo.flushMs 200, 10000, 1000 batching; when the buffer is full entries are dropped and counted, requests never wait on Mongo
redactKeys extra keys to redact

MongoDB documents

logs: _id, timestamp, level, message, service, environment, version, host, then every attribute of the entry (requestId, correlationId, ip, userAgent, userId, email, roles, sid, method, route, status, durationMs, error, stack, ...).

dau (time-series, meta = {userId, service, environment}): one row per access-log entry of a signed-in request (action = route) and per Event (action = event name), with status and logId pointing back to the logs entry. Unique users per day: group by day and $addToSet: "$meta.userId". Anonymous requests are never counted.

Building blocks

The pieces used by New are exported for custom setups: NewConsoleHandler, NewJSONHandler, NewContextHandler, Fanout (send one record to several handlers) and NewDailyFile (an io.WriteCloser with daily rotation).

License

MIT

Documentation

Index

Constants

View Source
const (
	LevelVerbose = slog.Level(-8)
	LevelDebug   = slog.LevelDebug
	LevelInfo    = slog.LevelInfo
	LevelWarn    = slog.LevelWarn
	LevelError   = slog.LevelError
)
View Source
const (
	CollectionLogs = "logs"
	CollectionDAU  = "dau"

	FieldUserID = "userId"
	FieldEvent  = "event"
	FieldRoute  = "route"
	FieldStatus = "status"

	Redacted = "[redacted]"
)
View Source
const (
	DefaultRetentionDays = 90
	DefaultBatchSize     = 200
	DefaultBufferSize    = 10000
	DefaultFlushInterval = time.Second
)

Variables

View Source
var DefaultRedactKeys = []string{
	"password", "newPassword", "currentPassword", "oldPassword", "confirmPassword", "passwordHash", "hash",
	"authorization", "cookie", "set-cookie", "token", "accessToken", "refreshToken", "idToken",
	"x-user-token", "x-refresh-token", "serviceToken", "secret", "clientSecret", "apiKey", "x-api-key",
	"privateKey", "otp",
}

Functions

func AttrsFrom

func AttrsFrom(ctx context.Context) []slog.Attr

func Err

func Err(err error) slog.Attr

func Event added in v0.2.0

func Event(ctx context.Context, log *slog.Logger, name string, attrs ...slog.Attr)

func Fanout

func Fanout(hs ...slog.Handler) slog.Handler

func LevelName

func LevelName(l slog.Level) string

func NewConsoleHandler

func NewConsoleHandler(w io.Writer, app string, min slog.Leveler, color bool) slog.Handler

func NewContextHandler

func NewContextHandler(next slog.Handler, redactKeys ...string) slog.Handler

func NewJSONHandler

func NewJSONHandler(w io.Writer, app string, min slog.Leveler) slog.Handler

func ParseLevel

func ParseLevel(s string) (slog.Level, error)

func WithAttrs

func WithAttrs(ctx context.Context, attrs ...slog.Attr) context.Context

func WithScope added in v0.2.0

func WithScope(ctx context.Context) context.Context

Types

type Config

type Config struct {
	LogDirectory    string      `json:"logDirectory"`
	ZippedArchive   bool        `json:"zippedArchive"`
	MinimumLogLevel string      `json:"minimumLogLevel" validate:"omitempty,oneof=error warn info debug verbose"`
	LogToFile       bool        `json:"logToFile"`
	LogToConsole    bool        `json:"logToConsole"`
	MaxFiles        int         `json:"maxFiles" validate:"min=0"`
	ConsoleColor    *bool       `json:"consoleColor,omitempty"`
	LogToMongo      bool        `json:"logToMongo"`
	Mongo           MongoConfig `json:"mongo"`
	RedactKeys      []string    `json:"redactKeys"`
}

func DefaultConfig

func DefaultConfig() Config

type DailyFile

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

func NewDailyFile

func NewDailyFile(o DailyFileOptions) (*DailyFile, error)

func (*DailyFile) Close

func (d *DailyFile) Close() error

func (*DailyFile) Write

func (d *DailyFile) Write(p []byte) (int, error)

type DailyFileOptions

type DailyFileOptions struct {
	Dir      string
	Pattern  string
	Symlink  string
	Compress bool
	MaxFiles int
	Now      func() time.Time
}

type Inserter added in v0.2.0

type Inserter interface {
	Insert(ctx context.Context, collection string, docs []any) error
	Close(ctx context.Context) error
}

type Logger

type Logger struct {
	*slog.Logger
	// contains filtered or unexported fields
}

func New

func New(cfg Config, app string, opts ...Option) (*Logger, error)

func (*Logger) Close

func (l *Logger) Close() error

func (*Logger) Verbose

func (l *Logger) Verbose(msg string, args ...any)

func (*Logger) VerboseContext

func (l *Logger) VerboseContext(ctx context.Context, msg string, args ...any)

type MongoConfig added in v0.2.0

type MongoConfig struct {
	URI           string `json:"uri"`
	Database      string `json:"database"`
	RetentionDays int    `json:"retentionDays" validate:"min=0"`
	BatchSize     int    `json:"batchSize" validate:"min=0"`
	BufferSize    int    `json:"bufferSize" validate:"min=0"`
	FlushMs       int    `json:"flushMs" validate:"min=0"`
}

type Option added in v0.2.0

type Option func(*settings)

func WithInserter added in v0.2.0

func WithInserter(i Inserter) Option

func WithMeta added in v0.2.0

func WithMeta(environment, version string) Option

Jump to

Keyboard shortcuts

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