Select Git revision
sqs-logs.go
sqs-logs.go 2.54 KiB
package logs
import (
"encoding/json"
"fmt"
"os"
"time"
"gitlab.com/uafrica/go-utils/errors"
"gitlab.com/uafrica/go-utils/logger"
)
//Call this at the end of an SQS event handler to capture the req and result as well as all actions taken during the processing
//(note: action list is only reset when this is called - so must be called after each handler, else action list has to be reset at the start)
func LogSQSRequest(startTime time.Time,
requestID string, //from API
messageType string,
req interface{},
handlerErr error,
) error {
if producer == nil {
return errors.Errorf("logs queue producer not set")
}
if !sqsLogEnabled {
return nil
}
endTime := time.Now()
log := ApiLog{
StartTime: startTime,
EndTime: endTime,
DurMs: endTime.Sub(startTime).Milliseconds(),
RequestID: requestID,
Method: "SQS",
Path: messageType,
}
if req != nil {
if reqString, ok := req.(string); ok {
log.Request.Body = reqString //do not marshal else we have double-escaped JSON
log.Request.BodySize = len(reqString)
} else {
if jsonReq, err := json.Marshal(req); err == nil {
log.Request.Body = string(jsonReq)
log.Request.BodySize = len(log.Request.Body)
}
}
}
if handlerErr == nil {
log.ResponseCode = 0
} else {
log.ResponseCode = 1
errorInfo := ErrorInfo{
Error: handlerErr.Error(),
Details: fmt.Sprintf("%+v", handlerErr),
}
jsonError, _ := json.Marshal(errorInfo)
log.Response.Body = string(jsonError)
}
//copy then reset actionList for the next handler
actionListMutex.Lock()
actionList = []ActionLog{}
actionListMutex.Unlock()
//todo: filter out sensitive values (e.g. OTP)
//note: we send SQS logs to "API_LOGS" which already exists... should be renamed to simply "LOGS"