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 ¶
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 ¶
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 ¶
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 ¶
Handle implements the slog.Handler interface and handles the Record. It will only be called when Enabled returns true.
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.