sloglambda

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: Unlicense Imports: 16 Imported by: ? modules, 0 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

slog-lambda

current codecov Doc License

AWS Lambda slog.Handler

A log/slog handler for AWS Lambda advanced logging controls.

Features
  • Auto-configures log format and level from Lambda environment variables (AWS_LAMBDA_LOG_FORMAT, AWS_LAMBDA_LOG_LEVEL)
  • JSON and text output formats
  • Includes Lambda metadata (function name, version, request ID) in log output
  • Supports custom log levels: TRACE and FATAL
  • Source code location in log records
Install
go get github.com/angryboat/slog-lambda
Usage
package main

import (
	"context"
	"log/slog"
	"os"

	"github.com/aws/aws-lambda-go/lambda"
	sloglambda "github.com/angryboat/slog-lambda"
)

func init() {
	logger := slog.New(sloglambda.NewHandler(os.Stdout))
	slog.SetDefault(logger)
}

func main() {
	lambda.Start(func(ctx context.Context, event any) error {
		slog.InfoContext(ctx, "Lambda Invoked", slog.Any("event", event))

		return nil
	})
}

By default, NewHandler reads AWS_LAMBDA_LOG_FORMAT and AWS_LAMBDA_LOG_LEVEL to configure itself. Use options to override:

handler := sloglambda.NewHandler(os.Stdout,
	sloglambda.WithJSON(),
	sloglambda.WithLevel(slog.LevelDebug),
	sloglambda.WithSource(),
	sloglambda.WithType("api.request"),
)
Options
Option Description
WithJSON() Output in JSON format
WithText() Output in text format
WithLevel(slog.Leveler) Set the minimum log level
WithSource() Include source file, function, and line number
WithType(string) Set the type field (default: "app.log")
WithoutTime() Omit the timestamp
Output

When using WithJSON(), log records look like:

{
  "level": "INFO",
  "msg": "Lambda Invoked",
  "record": {
    "functionName": "my-func",
    "version": "$LATEST",
    "requestId": "abc-123"
  },
  "type": "app.log"
}

When using WithText():

level="INFO" msg="Lambda Invoked" record.functionName="my-func" record.version="$LATEST" record.requestId="abc-123" type="app.log"

record and type are reserved. If your attrs or groups use either key at the top level, the handler's value wins and yours moves to the first unused key with underscores appended (type_, then type__, and so on).

Key Names and Lambda Conventions

Lambda documents two JSON shapes. System logs (platform events Lambda emits) use time, type, and record. Application logs from the managed runtimes' built-in loggers use timestamp, level, message, and requestId.

This handler mixes the two:

Key Source
level Lambda application-log key, used for log-level filtering
msg slog's default slog.MessageKey (Lambda's runtimes use message)
time slog's default slog.TimeKey, matching the system-log shape
type Borrowed from the system-log shape (default app.log)
record Borrowed from the system-log shape; holds function name, version, request ID

For log-level filtering, Lambda only requires a level key on a JSON object written to stdout or stderr, and the function's log format set to JSON. AWS says the timestamp must be RFC 3339 and its key should "follow the conventions of the runtime", without listing which key names it accepts. time values are RFC 3339 (time.RFC3339Nano).

There is no option to rename time. To emit timestamp instead, pass WithoutTime() and add the attr in a wrapping handler:

type timestampHandler struct{ slog.Handler }

func (h timestampHandler) Handle(ctx context.Context, r slog.Record) error {
	r.AddAttrs(slog.Time("timestamp", r.Time))
	return h.Handler.Handle(ctx, r)
}

func (h timestampHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
	return timestampHandler{h.Handler.WithAttrs(attrs)}
}

func (h timestampHandler) WithGroup(name string) slog.Handler {
	return timestampHandler{h.Handler.WithGroup(name)}
}

logger := slog.New(timestampHandler{sloglambda.NewHandler(os.Stdout, sloglambda.WithoutTime())})

WithAttrs and WithGroup must be overridden, or the wrapper drops out of any derived logger. Record attrs land in the innermost group, so on a logger built with WithGroup("g") the key becomes g.timestamp, not a top-level timestamp.

Log Levels

The handler maps AWS Lambda log levels to slog.Level values:

Lambda Level slog Level
TRACE slog.LevelDebug - 4
DEBUG slog.LevelDebug
INFO slog.LevelInfo (default)
WARN slog.LevelWarn
ERROR slog.LevelError
FATAL slog.LevelError + 4

Only these six names are guaranteed to work with Lambda's log-level filtering. A level between them renders as the nearest lower name plus an offset, e.g. slog.LevelInfo + 2 becomes INFO+2 and slog.LevelDebug - 8 becomes TRACE-4. AWS says an invalid or missing level is treated as INFO, but doesn't say whether INFO+2 counts as invalid. Don't rely on Lambda-side filtering for custom offsets; WithLevel filtering in the handler itself is unaffected.

Documentation

Overview

Package sloglambda is a slog.Handler for AWS Lambda functions.

It auto-configures log format (JSON or text) and level from Lambda's advanced logging environment variables. Options override env values.

Fields are written in a fixed order, matching slog.JSONHandler and slog.TextHandler: "time", "level", "source", "msg", then the handler's "type" and "record", then attrs and groups in the order they were added. Values that cannot be encoded as JSON are written as "!ERROR:<reason>" strings so a record is never dropped.

The handler reserves two top-level keys: "record" (Lambda function name, version, and request ID) and "type" (see WithType). When the handler sets one of these and an attr or group uses the same key at the top level, the handler's value wins and the caller's value moves to the first unused key formed by appending underscores ("record_", "type_", "type__", ...).

The rename is best-effort and has a few edge cases:

  • Two attrs with the same reserved key in one record both move to the same fallback key, so the output contains that key twice. This matches slog.JSONHandler, which also writes duplicate keys as given.
  • A top-level attr whose value is a slog.LogValuer counts as taken even if it resolves to an empty group and is never written, so the fallback may skip a key that ends up unused.
  • In text output, groups flatten into dotted keys, so a user key that already contains a dot ("record.requestId") is not renamed and lands in the same namespace as the handler's fields.
  • "time", "level", "msg", and "source" are not reserved. A user attr with one of those keys is written in addition to the built-in field, as slog.JSONHandler does.

See https://docs.aws.amazon.com/lambda/latest/dg/monitoring-logs.html

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Handler

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

Handler implements slog.Handler and writes structured log records to an io.Writer. Use NewHandler to create one.

func NewHandler

func NewHandler(w io.Writer, options ...Option) *Handler

NewHandler returns a Handler that writes to w.

By default it reads AWS_LAMBDA_LOG_LEVEL (TRACE, DEBUG, INFO, WARN, ERROR, FATAL), AWS_LAMBDA_LOG_FORMAT (json, text), AWS_LAMBDA_FUNCTION_NAME, and AWS_LAMBDA_FUNCTION_VERSION from the environment once, at construction. Any provided options take precedence over environment values.

Example
package main

import (
	"log/slog"
	"os"

	sloglambda "github.com/angryboat/slog-lambda"
)

func main() {
	handler := sloglambda.NewHandler(os.Stdout)
	logger := slog.New(handler)

	slog.SetDefault(logger)

	slog.Info("Hello, world!")
}

func (*Handler) Enabled

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

func (*Handler) Handle

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

func (*Handler) WithAttrs

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

func (*Handler) WithGroup

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

type Option

type Option func(*Handler)

Option configures a Handler. Pass options to NewHandler.

func WithFunctionName

func WithFunctionName(name string) Option

WithFunctionName sets the function name included in the "record" field. Defaults to the value of AWS_LAMBDA_FUNCTION_NAME. An empty name omits it.

func WithFunctionVersion

func WithFunctionVersion(version string) Option

WithFunctionVersion sets the function version included in the "record" field. Defaults to the value of AWS_LAMBDA_FUNCTION_VERSION. An empty version omits it.

func WithJSON

func WithJSON() Option

WithJSON sets the output format to JSON.

Example
package main

import (
	"log/slog"
	"os"

	sloglambda "github.com/angryboat/slog-lambda"
)

func main() {
	handler := sloglambda.NewHandler(os.Stdout, sloglambda.WithJSON(), sloglambda.WithoutTime())
	logger := slog.New(handler)

	slog.SetDefault(logger)

	slog.Info("Hello, world!")
}
Output:
{"level":"INFO","msg":"Hello, world!","type":"app.log","record":{"functionName":"test-function","version":"$LATEST"}}

func WithLevel

func WithLevel(level slog.Leveler) Option

WithLevel sets the minimum log level. Messages below this level are dropped. Defaults to the value of AWS_LAMBDA_LOG_LEVEL, or INFO if unset. A nil level means INFO, matching slog.HandlerOptions.

func WithSource

func WithSource() Option

WithSource adds caller information (function, file, line) to each log record.

func WithText

func WithText() Option

WithText sets the output format to key=value text.

Example
package main

import (
	"log/slog"
	"os"

	sloglambda "github.com/angryboat/slog-lambda"
)

func main() {
	handler := sloglambda.NewHandler(os.Stdout, sloglambda.WithText(), sloglambda.WithoutTime())
	logger := slog.New(handler)

	slog.SetDefault(logger)

	slog.Info("Hello, world!")
}
Output:
level="INFO" msg="Hello, world!" type="app.log" record.functionName="test-function" record.version="$LATEST"

func WithType

func WithType(logType string) Option

WithType sets the "type" field included in every log record. Defaults to "app.log".

func WithoutTime

func WithoutTime() Option

WithoutTime omits the timestamp from log output. Useful for testing or when CloudWatch already provides timestamps.

Jump to

Keyboard shortcuts

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