-
Notifications
You must be signed in to change notification settings - Fork 575
Adding structured logging helper #614
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+615
−0
Merged
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| //go:build go1.21 | ||
| // +build go1.21 | ||
|
|
||
| package lambdacontext_test | ||
|
|
||
| import ( | ||
| "context" | ||
| "log/slog" | ||
|
|
||
| "github.com/aws/aws-lambda-go/lambda" | ||
| "github.com/aws/aws-lambda-go/lambdacontext" | ||
| ) | ||
|
|
||
| // ExampleLogHandler demonstrates basic usage of LogHandler for structured logging. | ||
| // The handler automatically injects requestId from Lambda context into each log record. | ||
| func ExampleLogHandler() { | ||
| // Set up the Lambda-aware slog handler | ||
| slog.SetDefault(slog.New(lambdacontext.LogHandler())) | ||
|
anzheyazzz marked this conversation as resolved.
Outdated
|
||
|
|
||
| lambda.Start(func(ctx context.Context) (string, error) { | ||
| // Use slog.InfoContext to include Lambda context in logs | ||
| slog.InfoContext(ctx, "processing request", "action", "example") | ||
| return "success", nil | ||
| }) | ||
| } | ||
|
|
||
| // ExampleLogHandler_withFields demonstrates LogHandler with additional fields. | ||
| // Use WithFields with FieldFunctionARN() and FieldTenantID() to include extra context. | ||
| func ExampleLogHandler_withFields() { | ||
| // Set up handler with function ARN and tenant ID fields | ||
| slog.SetDefault(slog.New(lambdacontext.LogHandler( | ||
| lambdacontext.WithFields(lambdacontext.FieldFunctionARN(), lambdacontext.FieldTenantID()), | ||
| ))) | ||
|
anzheyazzz marked this conversation as resolved.
Outdated
|
||
|
|
||
| lambda.Start(func(ctx context.Context) (string, error) { | ||
| slog.InfoContext(ctx, "multi-tenant request", "tenant", "acme-corp") | ||
| return "success", nil | ||
| }) | ||
| } | ||
|
|
||
| // ExampleWithFields demonstrates using WithFields to include specific Lambda context fields. | ||
| func ExampleWithFields() { | ||
| // Include only function ARN | ||
| handler := lambdacontext.LogHandler( | ||
| lambdacontext.WithFields(lambdacontext.FieldFunctionARN()), | ||
| ) | ||
| slog.SetDefault(slog.New(handler)) | ||
|
|
||
| lambda.Start(func(ctx context.Context) (string, error) { | ||
| // Log output will include "functionArn" field | ||
| slog.InfoContext(ctx, "function invoked") | ||
| return "success", nil | ||
| }) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,148 @@ | ||
| //go:build go1.21 | ||
| // +build go1.21 | ||
|
|
||
| // Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
|
|
||
| package lambdacontext | ||
|
|
||
| import ( | ||
| "context" | ||
| "log/slog" | ||
| "os" | ||
| ) | ||
|
|
||
| // Field represents a Lambda context field to include in log records. | ||
| type Field struct { | ||
| key string | ||
| value func(*LambdaContext) string | ||
| } | ||
|
|
||
| // FieldFunctionARN returns a Field that includes the invoked function ARN in log records. | ||
| func FieldFunctionARN() Field { | ||
| return Field{"functionArn", func(lc *LambdaContext) string { return lc.InvokedFunctionArn }} | ||
| } | ||
|
|
||
| // FieldTenantID returns a Field that includes the tenant ID in log records (for multi-tenant functions). | ||
| func FieldTenantID() Field { | ||
| return Field{"tenantId", func(lc *LambdaContext) string { return lc.TenantID }} | ||
| } | ||
|
|
||
| // logOptions holds configuration for the Lambda log handler. | ||
| type logOptions struct { | ||
| fields []Field | ||
| } | ||
|
|
||
| // LogOption is a functional option for configuring the Lambda log handler. | ||
| type LogOption func(*logOptions) | ||
|
|
||
| // WithFields includes the specified fields in log records. | ||
| func WithFields(fields ...Field) LogOption { | ||
| return func(o *logOptions) { | ||
| o.fields = append(o.fields, fields...) | ||
| } | ||
| } | ||
|
|
||
| // LogHandler returns a [slog.Handler] for AWS Lambda structured logging. | ||
| // It reads AWS_LAMBDA_LOG_FORMAT and AWS_LAMBDA_LOG_LEVEL from environment, | ||
| // and injects requestId from Lambda context into each log record. | ||
| // | ||
| // By default, only requestId is injected. Use WithFields to include more. | ||
| // See the package examples for usage. | ||
| func LogHandler(opts ...LogOption) slog.Handler { | ||
|
anzheyazzz marked this conversation as resolved.
Outdated
|
||
| options := &logOptions{} | ||
| for _, opt := range opts { | ||
| opt(options) | ||
| } | ||
|
|
||
| level := parseLogLevel() | ||
| handlerOpts := &slog.HandlerOptions{ | ||
| Level: level, | ||
| ReplaceAttr: ReplaceAttr, | ||
| } | ||
|
|
||
| var h slog.Handler | ||
| if LogFormat == "JSON" { | ||
| h = slog.NewJSONHandler(os.Stdout, handlerOpts) | ||
| } else { | ||
| h = slog.NewTextHandler(os.Stdout, handlerOpts) | ||
| } | ||
|
|
||
| return &lambdaHandler{handler: h, fields: options.fields} | ||
| } | ||
|
|
||
| // ReplaceAttr maps slog's default keys to AWS Lambda's log format (time->timestamp, msg->message). | ||
| func ReplaceAttr(groups []string, attr slog.Attr) slog.Attr { | ||
| if len(groups) > 0 { | ||
| return attr | ||
| } | ||
|
|
||
| switch attr.Key { | ||
| case slog.TimeKey: | ||
| attr.Key = "timestamp" | ||
| case slog.MessageKey: | ||
| attr.Key = "message" | ||
| } | ||
| return attr | ||
| } | ||
|
|
||
| // Attrs returns Lambda context fields as slog-compatible key-value pairs. | ||
| // For most use cases, using [LogHandler] with slog.InfoContext is preferred. | ||
| func (lc *LambdaContext) Attrs() []any { | ||
| return []any{"requestId", lc.AwsRequestID} | ||
| } | ||
|
anzheyazzz marked this conversation as resolved.
Outdated
|
||
|
|
||
| // lambdaHandler wraps a slog.Handler to inject Lambda context fields. | ||
| type lambdaHandler struct { | ||
| handler slog.Handler | ||
| fields []Field | ||
| } | ||
|
|
||
| // Enabled implements slog.Handler. | ||
| func (h *lambdaHandler) Enabled(ctx context.Context, level slog.Level) bool { | ||
| return h.handler.Enabled(ctx, level) | ||
| } | ||
|
|
||
| // Handle implements slog.Handler. | ||
| func (h *lambdaHandler) Handle(ctx context.Context, r slog.Record) error { | ||
|
anzheyazzz marked this conversation as resolved.
|
||
| if lc, ok := FromContext(ctx); ok { | ||
| r.AddAttrs(slog.String("requestId", lc.AwsRequestID)) | ||
|
anzheyazzz marked this conversation as resolved.
|
||
|
|
||
| for _, field := range h.fields { | ||
| if v := field.value(lc); v != "" { | ||
| r.AddAttrs(slog.String(field.key, v)) | ||
| } | ||
| } | ||
| } | ||
| return h.handler.Handle(ctx, r) | ||
| } | ||
|
|
||
| // WithAttrs implements slog.Handler. | ||
| func (h *lambdaHandler) WithAttrs(attrs []slog.Attr) slog.Handler { | ||
| return &lambdaHandler{ | ||
| handler: h.handler.WithAttrs(attrs), | ||
| fields: h.fields, | ||
| } | ||
| } | ||
|
|
||
| // WithGroup implements slog.Handler. | ||
| func (h *lambdaHandler) WithGroup(name string) slog.Handler { | ||
| return &lambdaHandler{ | ||
| handler: h.handler.WithGroup(name), | ||
| fields: h.fields, | ||
| } | ||
| } | ||
|
|
||
| func parseLogLevel() slog.Level { | ||
| switch LogLevel { | ||
| case "DEBUG": | ||
| return slog.LevelDebug | ||
| case "INFO": | ||
| return slog.LevelInfo | ||
| case "WARN": | ||
| return slog.LevelWarn | ||
| case "ERROR": | ||
| return slog.LevelError | ||
| default: | ||
| return slog.LevelInfo | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.