slogalert

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2026 License: MIT Imports: 9 Imported by: 0

README

slogalert

An slog.Handler that mirrors ERROR-level (or higher) log records to a chat webhook (Google Chat, Slack, or anything that accepts a JSON body) while passing every record through to an inner handler unchanged.

Wrap it once at logger setup and existing slog.Error(...) calls start alerting; no call-site changes needed.

Install

go get github.com/clusterity/slogalert

Use

import (
	"log/slog"
	"os"

	"github.com/clusterity/slogalert"
)

func setupLogging(webhook string) {
	var h slog.Handler = slog.NewJSONHandler(os.Stdout, nil)

	// Enable alerting only when a webhook is configured (e.g. in production).
	h = slogalert.NewHandler(h, slogalert.Options{
		WebhookURL:  webhook, // empty -> NewHandler returns the inner handler unchanged
		ServiceName: "hindsight",
	})

	slog.SetDefault(slog.New(h))
}

slogalert is config-agnostic: it reads no environment variables. Each caller decides when to enable it and where the webhook comes from.

Options

Field Default Notes
WebhookURL none Required. Empty returns the inner handler unchanged.
ServiceName "" Shown in the formatted alert.
MinLevel slog.LevelError A slog.Leveler; pass slog.LevelWarn to lower it.
Debounce time.Minute Collapses repeat alerts with the same message. Negative disables.
Format GoogleChatText Renders the request body; swap for Slack blocks, Discord, etc.
Client &http.Client{Timeout: 10s} The HTTP client used to POST.

Behaviour

  • Sends run in a detached goroutine, so logging never blocks on the webhook.
  • Debouncing is keyed on the message string and applied before a goroutine is spawned, so repeat-error floods stay cheap.
  • Sends are fire-and-forget: in-flight alerts are dropped if the process exits.
  • Webhook failures are swallowed so alerting can't break logging.

Custom formatter

slogalert.Options{
	WebhookURL: webhook,
	Format: func(e slogalert.Event) ([]byte, error) {
		return json.Marshal(map[string]any{
			"text": fmt.Sprintf("[%s] %s: %s", e.Service, e.Level, e.Message),
		})
	},
}

License

MIT

Documentation

Overview

Package slogalert provides an slog.Handler that mirrors error-level records to a chat webhook (Google Chat, Slack, or any JSON endpoint) while passing every record to an inner handler.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GoogleChatText

func GoogleChatText(e Event) ([]byte, error)

GoogleChatText renders a plain-text alert as {"text": ...}, the shape Google Chat and Slack incoming webhooks both accept.

func NewHandler

func NewHandler(inner slog.Handler, opts Options) slog.Handler

NewHandler wraps inner to also send records at or above MinLevel to the webhook. An empty WebhookURL returns inner unchanged.

Types

type Event

type Event struct {
	Time    time.Time
	Level   slog.Level
	Message string
	Service string
	Attrs   []slog.Attr
}

Event is the alert payload: the triggering record plus merged attrs.

type FormatFunc

type FormatFunc func(Event) ([]byte, error)

FormatFunc renders an Event into a webhook request body.

type Handler

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

Handler decorates an inner handler, mirroring records at or above MinLevel to the webhook.

func (*Handler) Enabled

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

Enabled reports whether the inner handler accepts level or level alerts.

func (*Handler) Handle

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

Handle passes the record to inner and, at or above MinLevel, sends an alert.

func (*Handler) WithAttrs

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

WithAttrs returns a new Handler with the given attributes.

func (*Handler) WithGroup

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

WithGroup returns a new Handler qualified with the given group.

type Options

type Options struct {
	WebhookURL  string
	ServiceName string

	// MinLevel is the level at or above which records alert.
	// Nil defaults to slog.LevelError.
	MinLevel slog.Leveler

	// Debounce collapses repeat alerts with the same message.
	// Zero defaults to one minute; negative disables debouncing.
	Debounce time.Duration

	// Format renders the webhook request body. Nil defaults to GoogleChatText.
	Format FormatFunc

	// Client posts the alert. Nil defaults to a client with a 10s timeout.
	Client *http.Client
}

Options configures a Handler. Only WebhookURL is required.

Jump to

Keyboard shortcuts

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