slogloki

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2025 License: MIT Imports: 14 Imported by: 0

README

slog-loki

Zero dependency slog-handler for Loki.

A chaining, context-aware slog.Handler that pushes structured logs to Loki with batching, gzip, smart retries, and graceful shutdown.


Install

go get github.com/bearsoft-fi/slogloki

Basic usage

package main

import (
	"log/slog"

	"github.com/bearsoft-fi/slogloki"
)

func main() {
	config := slogloki.NewDefaultConfig(
		"http://localhost:3100/loki/api/v1/push",
		slogloki.WithTenantID("tenant1"),
	)

	// Labels defined during init are sent as stream tags
	handler, _ := slogloki.NewLokiHandler(config, map[string]string{
		"job":     "myapp",
		"service": "auth",
	})
	// Don't forget to close so last pending messages are flushed cleanly
	defer handler.Close()

	slog.SetDefault(slog.New(handler))

	// This will create a log message with attributes inserted into the log line itself
	slog.Info("login success",
		slog.Group("user",
			slog.String("id", "123"),
			slog.String("name", "Matti"),
		),
		slog.String("ip", "1.2.3.4"),
	)

	// Any attributes defined using `With` will be added as structured metadata
	slog.
		With("tag", "api.sql").
		With("query.statement", "SELECT COUNT(*) FROM users;").
		With("query.duration", 1*time.Second).
		With("error", fmt.Errorf("could not count users")).
		Error("Oh no!")
}

Features

  • Zero external dependencies
  • Full slog.Handler interface
  • Batched pushes (defaults 512 or 500ms)
  • Smart gzip (only >300 bytes)
  • Exponential backoff + support for Retry-After HTTP header
  • Graceful shutdown (flush on close)
  • In-memory queue (default 10k entries)

Documentation

Index

Constants

View Source
const (
	BatchWait        = 500 * time.Millisecond
	BatchSize    int = 512
	MinBackoff       = 500 * time.Millisecond
	MaxBackoff       = 5 * time.Minute
	MaxRetries   int = 10
	Timeout          = 10 * time.Second
	QueueMaxSize int = 10 * 1024
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AttrAdapter

type AttrAdapter struct {
	Name, Value string
}

type AttrsAdapter

type AttrsAdapter []AttrAdapter

func (AttrsAdapter) MarshalJSON

func (ls AttrsAdapter) MarshalJSON() ([]byte, error)

Marshal as a map

type Config

type Config struct {
	// HTTP host
	URL string

	// Log level
	Level slog.Leveler

	// X-Scope-OrgID
	TenantID string

	// Batch size and max wait time
	BatchSize int
	BatchWait time.Duration

	// Local queue size
	QueueMaxSize int

	// Backoff/retries
	MinBackoff time.Duration
	MaxBackoff time.Duration
	MaxRetries int

	// Timeout
	Timeout time.Duration
}

func NewDefaultConfig

func NewDefaultConfig(url string, opts ...Option) *Config

type LokiHandler

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

func NewLokiHandler

func NewLokiHandler(config *Config, labels map[string]string) (*LokiHandler, error)

func (*LokiHandler) Close

func (h *LokiHandler) Close() error

func (*LokiHandler) Enabled

func (h *LokiHandler) Enabled(ctx context.Context, level slog.Level) bool

--- slog.Handler interface ---

func (*LokiHandler) Handle

func (h *LokiHandler) Handle(ctx context.Context, r slog.Record) error

func (*LokiHandler) WithAttrs

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

func (*LokiHandler) WithGroup

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

type LokiNextHandler

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

func (*LokiNextHandler) Enabled

func (h *LokiNextHandler) Enabled(ctx context.Context, level slog.Level) bool

func (*LokiNextHandler) Handle

func (h *LokiNextHandler) Handle(ctx context.Context, r slog.Record) error

Multi-level support for WithGroup and WithAttrs

func (*LokiNextHandler) WithAttrs

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

func (*LokiNextHandler) WithGroup

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

type Option

type Option func(config *Config)

func WithLevel

func WithLevel(level slog.Leveler) Option

func WithTenantID

func WithTenantID(id string) Option

Jump to

Keyboard shortcuts

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