Skip to content

Instantly share code, notes, and snippets.

@kmesiab
Created January 4, 2024 17:44
Show Gist options
  • Save kmesiab/94663886c5936da3f7132c2da6a1545d to your computer and use it in GitHub Desktop.
Save kmesiab/94663886c5936da3f7132c2da6a1545d to your computer and use it in GitHub Desktop.
Simple Logger in Go
package lib
import (
"encoding/json"
"fmt"
"log"
"github.com/aws/aws-lambda-go/events"
api "github.com/twilio/twilio-go/rest/api/v2010"
"github.com/kmesiab/go-fortune-teller/lambdas/models"
)
// JSONMessage is a struct that represents a map of
// key/value pairs that can be marshalled into JSON.
// A "message" property is always present in the map,
// but additional key/value pairs can be added using
// the Add() method. Additional types, like errors and
// TwilioMessageInfo structs, can be added using the AddError()
// and AddTwilioMessageInfo() methods, respectively.
type JSONMessage struct {
Message string `json:"message"`
Fields map[string]string `json:"data,omitempty"`
Logger *log.Logger `json:"-"`
}
// NewMsgf creates a new JSONMessage struct.
// The typical usage is:
// NewMsgf("Hello, %s", "World").Add("key", "value").Respond(200)
// NewMsgf("Hello, %s", "World").AddError(err).Log
// s := NewMsgf("Hello, %s", "World").Write()
func NewMsgf(format string, a ...interface{}) *JSONMessage {
return &JSONMessage{
Message: fmt.Sprintf(format, a...),
Fields: make(map[string]string),
Logger: log.Default(),
}
}
// Add a key/value pair
func (r *JSONMessage) Add(key string, value string) *JSONMessage {
r.Fields[key] = value
return r
}
// Pack an error. Optionally you can fetch the error's stack trace
// and enrich the response
func (r *JSONMessage) AddError(err error) *JSONMessage {
if err != nil {
r.Add("error", err.Error())
}
return r
}
// Create a custom object unpacker for logging details
func (r *JSONMessage) AddSQSEvent(event *events.SQSMessage) *JSONMessage {
return r.Add("message_id", event.MessageId).
Add("md5_of_body", event.Md5OfBody).
Add("event_source", event.EventSource).
Add("event_source_arn", event.EventSourceARN).
Add("aws_region", event.AWSRegion).
Add("md5_of_attributes", event.Md5OfMessageAttributes).
Add("receipt_handle", event.ReceiptHandle).
Add("body", event.Body)
}
// Returns the contents as a json string
func (r *JSONMessage) Write() string {
s, err := json.Marshal(r)
if err != nil {
log.Fatalf("Error marshalling response: %s\n", err)
return r.Message
}
return string(s)
}
// Optionally create a mechanism to pipe the output as an HTTP Response
func (r *JSONMessage) Respond(status int) (events.APIGatewayProxyResponse, error) {
logEntry := r.Write()
return events.APIGatewayProxyResponse{
Headers: DefaultHttpHeaders,
StatusCode: status,
Body: logEntry,
}, nil
}
// Wrap log levels below, for instance a broad default log message:
func (r *JSONMessage) Log() {
logEntry := r.Write()
log.Println(logEntry)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment