Skip to content

Instantly share code, notes, and snippets.

@napicella
Last active January 3, 2021 13:28
Show Gist options
  • Save napicella/b38db97b50da2c93230d0322c89629a2 to your computer and use it in GitHub Desktop.
Save napicella/b38db97b50da2c93230d0322c89629a2 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"net/http"
"time"
"github.com/aws/aws-lambda-go/lambda"
"github.com/prozz/aws-embedded-metrics-golang/emf"
)
type loggingRoundTripper struct {
Proxied http.RoundTripper
}
func (t loggingRoundTripper) RoundTrip(req *http.Request) (res *http.Response, e error) {
m := emf.New().Namespace("CustomNamespace")
defer m.Log()
start := time.Now()
res, e = t.Proxied.RoundTrip(req)
elapsed := time.Since(start)
m.DimensionSet(
emf.NewDimension("Endpoint", req.Host),
emf.NewDimension("Operation", req.Method)).
MetricFloatAs("Duration", elapsed.Seconds(), emf.Seconds)
clientErr := 0
serverErr := 0
success := 0
if res.StatusCode >= 200 && res.StatusCode < 300 {
success = 1
}
if res.StatusCode >= 500 {
serverErr = 1
}
if res.StatusCode >= 400 && res.StatusCode < 500 {
clientErr = 1
}
m.MetricAs("Error", clientErr, emf.Count)
m.MetricAs("Fatal", serverErr, emf.Count)
m.MetricAs("Success", success, emf.Count)
return
}
func handler(ctx context.Context, event MyEvent) (string, error) {
var c = &http.Client{Transport: loggingRoundTripper{http.DefaultTransport}}
c.Get(event.URL)
return "done", nil
}
func main() {
lambda.Start(handler)
}
type MyEvent struct {
URL string `json:"url"`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment