Select Git revision
api-logs.go
api-logs.go 5.37 KiB
package logs
import (
"net/http"
"sort"
"strings"
"time"
"github.com/aws/aws-lambda-go/events"
"gitlab.com/uafrica/go-utils/errors"
"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)
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["user_id"].(string)
accountID, _ := claim["account_id"].(int64)
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,
UserAgent: req.RequestContext.Identity.UserAgent,
Username: username,
AccountID: accountID,
Request: ApiLogRequest{
Headers: req.Headers,
QueryParameters: req.QueryStringParameters,
BodySize: len(req.Body),
Body: req.Body,
},
Response: ApiLogResponse{