categraf/logs/processor/json_serverless.go

73 lines
2.1 KiB
Go
Raw Normal View History

2022-05-31 01:23:19 +08:00
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
package processor
import (
"encoding/json"
"time"
2022-06-02 19:55:13 +08:00
"flashcat.cloud/categraf/logs/message"
2022-05-31 01:23:19 +08:00
)
// JSONServerlessEncoder is a shared json encoder sending a struct message field
// instead of a bytes message field. This encoder is used in the AWS Lambda
// serverless environment.
var JSONServerlessEncoder Encoder = &jsonServerlessEncoder{}
// jsonEncoder transforms a message into a JSON byte array.
type jsonServerlessEncoder struct{}
// JSON representation of a message.
type jsonServerlessPayload struct {
Message jsonServerlessMessage `json:"message"`
Status string `json:"status"`
Timestamp int64 `json:"timestamp"`
Hostname string `json:"hostname"`
Service string `json:"service,omitempty"`
2022-06-02 16:52:56 +08:00
Source string `json:"fcsource"`
Tags string `json:"fctags"`
2022-05-31 01:23:19 +08:00
}
type jsonServerlessMessage struct {
Message string `json:"message"`
Lambda *jsonServerlessLambda `json:"lambda,omitempty"`
}
type jsonServerlessLambda struct {
ARN string `json:"arn"`
RequestID string `json:"request_id,omitempty"`
}
// Encode encodes a message into a JSON byte array.
func (j *jsonServerlessEncoder) Encode(msg *message.Message, redactedMsg []byte) ([]byte, error) {
ts := time.Now().UTC()
if !msg.Timestamp.IsZero() {
ts = msg.Timestamp
}
// add lambda metadata
var lambdaPart *jsonServerlessLambda
if l := msg.Lambda; l != nil {
lambdaPart = &jsonServerlessLambda{
ARN: l.ARN,
RequestID: l.RequestID,
}
}
return json.Marshal(jsonServerlessPayload{
Message: jsonServerlessMessage{
Message: toValidUtf8(redactedMsg),
Lambda: lambdaPart,
},
Status: msg.GetStatus(),
Timestamp: ts.UnixNano() / nanoToMillis,
Hostname: msg.GetHostname(),
Service: msg.Origin.Service(),
Source: msg.Origin.Source(),
Tags: msg.Origin.TagsToString(),
})
}