Select Git revision
api-logs.go
-
Jan Semmelink authoredJan Semmelink authored
api-logs.go 5.71 KiB
package logs
import (
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/aws/aws-lambda-go/events"
"gitlab.com/uafrica/go-utils/errors"
"gitlab.com/uafrica/go-utils/logger"
"gitlab.com/uafrica/go-utils/queues"
)
var producer queues.Producer
func Init(p queues.Producer) {
producer = p
}
//Call this at the end of an API request handler to capture the req/res 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 LogIncomingAPIRequest(startTime time.Time, requestID string, claim map[string]interface{}, req events.APIGatewayProxyRequest, res events.APIGatewayProxyResponse) error {
if producer == nil {
return errors.Errorf("logs queue producer not set")
}
//todo: filter out some noisy (method+path)
logger.Debugf("claim: %+v", claim)
endTime := time.Now()
var authType string
var authUsername string
if req.RequestContext.Identity.CognitoAuthenticationType != "" {
authType = "cognito"
split := strings.Split(req.RequestContext.Identity.CognitoAuthenticationProvider, ":")
if len(split) > 0 {
authUsername = split[len(split)-1] //= part after last ':'
}
} else {
authType = "iam"
split := strings.Split(req.RequestContext.Identity.UserArn, ":user/")
if len(split) > 0 {
authUsername = split[len(split)-1] //= part after ':user/'
}
}
username, _ := claim["Username"].(string)
accountID, _ := claim["AccountID"].(int64)
if accountID == 0 {
if accountIDParam, ok := req.QueryStringParameters["account_id"]; ok {
if i64, err := strconv.ParseInt(accountIDParam, 10, 64); err == nil && i64 > 0 {
accountID = i64
}
}
}
apiLog := ApiLog{
StartTime: startTime,
EndTime: endTime,
DurMs: endTime.Sub(startTime).Milliseconds(),
Method: req.HTTPMethod,
Address: req.RequestContext.DomainName,
Path: req.Path,
ResponseCode: res.StatusCode,
RequestID: requestID,
InitialAuthType: authType,
InitialAuthUsername: authUsername,
SourceIP: req.RequestContext.Identity.SourceIP,