powerslog

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 12 Imported by: 1 module, 1 package

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

Powerslog

A slog handler that captures key fields from an AWS Lambda context and produces structured logs with the same fields as the Powertools loggers for Python and TypeScript.

Getting started

Requirements
  • Go 1.27+
Installation and usage
package main

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

    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
    "github.com/unfunco/powerslog"
)

func newHandler(logger *slog.Logger) func(context.Context, events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    return func(ctx context.Context, event events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
        logger.InfoContext(ctx, "Request received",
            slog.String("method", event.HTTPMethod),
            slog.String("resource", event.Resource),
        )

        return events.APIGatewayProxyResponse{
            StatusCode: http.StatusNoContent,
        }, nil
    }
}

func main() {
    logger := slog.New(powerslog.NewHandler(os.Stdout, nil))

    lambda.Start(newHandler(logger))
}

The per-invocation fields are read from the context, so use the *Context logging methods, such as InfoContext, with the context passed to the function handler.

Fields
Key Source
timestamp The time of the record, in UTC
level The level of the record
message The message of the record
location The log statement, with AddSource
service POWERTOOLS_SERVICE_NAME
function_name AWS_LAMBDA_FUNCTION_NAME
function_memory_size AWS_LAMBDA_FUNCTION_MEMORY_SIZE
sampling_rate The sample rate, when sampling is enabled
function_request_id The Lambda context
function_arn The Lambda context
cold_start The Lambda context
xray_trace_id The Lambda context, or _X_AMZN_TRACE_ID

As with the handlers in log/slog, duplicate keys are not removed, so avoid adding top-level attributes with these names, or add them to a group.

cold_start is true for the first invocation whose context reaches the handler, so it is only reliable when the first invocation makes at least one *Context logging call, at any level.

Configuration

The handler is configured with powerslog.Options and the same environment variables as the Powertools loggers.

Environment variable Description
AWS_LAMBDA_LOG_LEVEL Level, overrides Options.Level
POWERTOOLS_LOG_LEVEL Level, when Options.Level is nil
POWERTOOLS_LOGGER_SAMPLE_RATE Sample rate, when SampleRate is 0
POWERTOOLS_SERVICE_NAME Value of the service field

The level is one of TRACE, DEBUG, INFO, WARN, ERROR, FATAL or SILENT, and defaults to INFO. The sample rate is the probability, from 0 to 1, that an invocation also logs its DEBUG records.

Development and testing
go test -race ./...

The lambda directory contains a function for testing in AWS.

cd lambda
GOOS=linux GOARCH=arm64 go build -tags lambda.norpc -o bootstrap main.go
sam deploy --guided

License

© 2024 Daniel Morris
Made available under the terms of the MIT License.

Documentation

Overview

Package powerslog provides a slog.Handler implementation designed for use with AWS Lambda functions and captures key fields from the Lambda context, it is intended to be functionally similar to the Powertools loggers for Python and TypeScript whilst remaining idiomatic for the Go programming language.

The per-invocation fields (function_request_id, function_arn, cold_start and xray_trace_id) are read from the context passed to the handler, so the *Context logging methods, such as slog.Logger.InfoContext, must be used with the context passed to the Lambda function handler to include them.

The cold start is attributed to the first invocation whose context reaches the handler, whether or not the record is logged. If the first invocation makes no such logging call, the next invocation that does is reported as the cold start instead.

The handler writes the timestamp, level, message, location, service, function_name, function_memory_size, sampling_rate, function_request_id, function_arn, cold_start and xray_trace_id keys at the top level of each record. Like the handlers in log/slog, it does not remove duplicate keys, so an attribute added at the top level under one of these names is written in addition to the handler's own.

Example
package main

import (
	"log/slog"
	"os"

	"github.com/unfunco/powerslog"
)

func main() {
	_ = os.Setenv("AWS_LAMBDA_FUNCTION_NAME", "example-logging-function")
	_ = os.Setenv("AWS_LAMBDA_FUNCTION_MEMORY_SIZE", "256")
	_ = os.Setenv("POWERTOOLS_SERVICE_NAME", "example-logging-service")

	// Remove the time from the output, this makes it easier to test.
	logger := slog.New(powerslog.NewHandler(os.Stdout, &powerslog.Options{
		Level:       slog.LevelDebug,
		ReplaceAttr: removeTimeAttr(),
	}))

	logger.Debug("This is a debug message!")
	logger.Info("This is an informational message!")
	logger.Warn("This is a warning message!")
	logger.Error("This is an error message!")

}

func removeTimeAttr() func(groups []string, a slog.Attr) slog.Attr {
	return func(groups []string, a slog.Attr) slog.Attr {
		if a.Key == "timestamp" && len(groups) == 0 {
			return slog.Attr{}
		}
		return a
	}
}
Output:
{"level":"DEBUG","message":"This is a debug message!","service":"example-logging-service","function_name":"example-logging-function","function_memory_size":256}
{"level":"INFO","message":"This is an informational message!","service":"example-logging-service","function_name":"example-logging-function","function_memory_size":256}
{"level":"WARN","message":"This is a warning message!","service":"example-logging-service","function_name":"example-logging-function","function_memory_size":256}
{"level":"ERROR","message":"This is an error message!","service":"example-logging-service","function_name":"example-logging-function","function_memory_size":256}

Index

Examples

Constants

View Source
const (
	LevelTrace slog.Level = slog.LevelDebug - 4
	LevelFatal slog.Level = slog.LevelError + 4
)

Levels in addition to those defined by slog, matching the TRACE and FATAL levels supported by Lambda and the Powertools loggers.

Variables

This section is empty.

Functions

This section is empty.

Types

type Handler

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

Handler is a slog.Handler that writes JSON records and adds key fields from the AWS Lambda environment and invocation context to every record.

func NewHandler

func NewHandler(w io.Writer, opts *Options) *Handler

NewHandler creates a Handler that writes JSON records to w and adds the service name, function name and function memory size attributes, where set, since these values do not change during the lifetime of the handler.

The function request ID, function ARN, cold start and X-Ray trace ID are added to each record from the context passed to the *Context logging methods, such as slog.Logger.InfoContext. The X-Ray trace ID falls back to the _X_AMZN_TRACE_ID environment variable when it is not in the context.

When the sample rate is greater than 0, it is added to every record as the sampling_rate attribute.

func (*Handler) Enabled

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

Enabled reports whether the handler handles records at the given level. The handler ignores records whose level is lower, except for debug records in a sampled invocation.

func (*Handler) Handle

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

Handle implements the slog.Handler interface and handles the Record. It will only be called when Enabled returns true.

func (*Handler) WithAttrs

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

WithAttrs returns a new Handler whose attributes consist of both the receiver's attributes and the arguments.

func (*Handler) WithGroup

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

WithGroup returns a new Handler with the given group appended to the receiver's existing groups.

type Options added in v0.2.0

type Options struct {
	// Level is the minimum level of records to log. The AWS_LAMBDA_LOG_LEVEL
	// environment variable takes precedence over Level, and the
	// POWERTOOLS_LOG_LEVEL environment variable is used when Level is nil.
	// Defaults to [slog.LevelInfo].
	//
	// The environment variables accept TRACE, DEBUG, INFO, WARN or WARNING,
	// ERROR, FATAL or CRITICAL, and SILENT, in any case. Any other value is
	// ignored.
	Level slog.Leveler

	// SampleRate is the probability, from 0 to 1, that an invocation is
	// sampled, which logs its debug records regardless of the level. The
	// decision is made from the request ID, so it is the same for every
	// record in an invocation. When SampleRate is 0 or outside [0, 1], the
	// POWERTOOLS_LOGGER_SAMPLE_RATE environment variable is used.
	SampleRate float64

	// AddSource adds the source code position of the log statement to the output.
	AddSource bool

	// ReplaceAttr is called to rewrite each non-group attribute before it is
	// logged, see [slog.HandlerOptions]. It is called after the built-in
	// attributes have been renamed, so it sees the timestamp, message and
	// location keys rather than the time, msg and source keys.
	ReplaceAttr func(groups []string, a slog.Attr) slog.Attr
}

Options configures a Handler. A nil *Options is equivalent to the zero value.

Directories

Path Synopsis
lambda module

Jump to

Keyboard shortcuts

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