Skip to content

dougEfresh/lambdazap

Repository files navigation

Lambda Zap

Add AWS lamba context fields to Uber's Zap

GoDoc Build Status Coverage Status Go Report

Installation

$ go get -u github.com/dougEfresh/lambdazap

Quick Start

package main
import (
    "context"

    "github.com/aws/aws-lambda-go/lambda"
    "github.com/dougEfresh/lambdazap"
    "go.uber.org/zap"
    "go.uber.org/zap/zapcore"
)

// Create a new lambda log context and use RequestID, FunctionName, InvokeFunctionArn and a variable from environment
var lambdazapper = lambdazap.New().
    With(lambdazap.AwsRequestID, lambdazap.FunctionName, lambdazap.InvokeFunctionArn).
    WithEnv("ZAP_TEST")

var logger *zap.Logger

func init() {
    // Init the logger outside of the handler
    logger, _ := zap.NewProduction()
}

func Handler(ctx context.Context) (string, error) {
     defer logger.Sync()
    logger.Info("Starting hander with context values ", lambdazapper.ContextValues(ctx)...)
    return "Uber zap with lambda context", nil
}

func main() {
    lambda.Start(Handler)
}

Usage

There are some non context fields such as FunctionName which you can add to all logging requests

lambdazapper := New(lambdazap.ProcessNonContextFields(false)).With(lambdazap.FunctionName, lambdazap.FunctionVersion, lambdazap.AwsRequestID)
logger.With(lambdazapper.NonContextValues()...))
logger.Info("only non context values")

The above will log FunctionName and FunctionVersion but not RequestId.

The Non Context fields are

FunctionName
FunctionVersion
LogGroupName
LogStreamName
MemoryLimitInMB

Note by default all context and non context will be logged. The option lambdazap.ProcessNonContextFields(false) will NOT log non context values (e.g. FunctionName) when used like this

logger.Info("only context values. No FunctionName!", lambdazapper.ContextValues()...)

Examples

See example handler with cloudformation.

List of fields

Prerequisites

go 1.x

Tests

$ go test -v

See travis.yaml for running benchmark tests

Benchmarks

In the spirit of Uber's zap logger, zero allocations are used:

Type Time Objects Allocated
Non Context ~150 ns/op 0 allocs/op
With Basic ~400 ns/op 0 allocs/op
With All ~733 ns/op 0 allocs/op

Deployment

Contributing

All PRs are welcome

Authors

License

This project is licensed under the Apache License - see the LICENSE file for details

Acknowledgments

TODO