Created
January 2, 2022 21:59
-
-
Save erayakartuna/18ceece6e89507ca1465b02df1efbbc6 to your computer and use it in GitHub Desktop.
final
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package log | |
import ( | |
"bytes" | |
"encoding/json" | |
"fmt" | |
"github.com/aws/aws-sdk-go/aws" | |
"github.com/aws/aws-sdk-go/aws/session" | |
"github.com/aws/aws-sdk-go/service/s3" | |
"sync" | |
"time" | |
) | |
type requestLogs struct { | |
logs []string | |
sync.Mutex | |
} | |
var reqLogs requestLogs | |
// InitRequestLogs ... | |
func InitRequestLogs() { | |
go func() { | |
for { | |
time.Sleep(time.Second * 5) | |
writeLogs() | |
} | |
}() | |
} | |
func writeLogs() { | |
if len(reqLogs.logs) == 0 { | |
return | |
} | |
reqLogs.Lock() | |
tmp := append(reqLogs.logs[:0:0], reqLogs.logs...) | |
reqLogs.logs = nil | |
reqLogs.Unlock() | |
file := new(bytes.Buffer) | |
for _, v := range tmp { | |
_, _ = file.WriteString(v) | |
} | |
// write to s3 | |
sess := session.Must(session.NewSession()) | |
sess.Config.Region = aws.String("eu-west-1") | |
client := s3.New(sess) | |
_, _ = client.PutObject(&s3.PutObjectInput{ | |
Bucket: aws.String("bucket-name"), | |
Key: aws.String(fmt.Sprintf("%s.json", time.Now().String())), | |
Body: bytes.NewReader(file.Bytes()), | |
ContentType: aws.String("text/json"), | |
ContentDisposition: aws.String("attachment"), | |
ServerSideEncryption: aws.String("AES256"), | |
ACL: aws.String("private"), | |
}) | |
} | |
func Request(url string, reqBody string, respStatus int, resp string) { | |
l := fmt.Sprintf( | |
`{"url": "%s", "reqBody": "%s", "respStatus": "%d", "resp": "%s"\n\r`, | |
jsonEscape(url), | |
jsonEscape(reqBody), | |
respStatus, | |
jsonEscape(resp), | |
) | |
reqLogs.Lock() | |
reqLogs.logs = append(reqLogs.logs, l) | |
reqLogs.Unlock() | |
} | |
// jsonEscape ... | |
func jsonEscape(i string) string { | |
b, err := json.Marshal(i) | |
if err != nil { | |
Fatal(err) | |
} | |
s := string(b) | |
return s[1 : len(s)-1] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment