Created
January 2, 2022 20:37
-
-
Save erayakartuna/d1f7af916ed263c4eac78fb35ca06c25 to your computer and use it in GitHub Desktop.
Logv2.go
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
type requestLogs struct { | |
logs []string | |
sync.Mutex | |
} | |
var reqLogs requestLogs | |
// InitRequestLogs ... | |
func InitRequestLogs() { | |
go func() { | |
for { | |
time.Sleep(time.Second * 5) | |
writeLogs() | |
} | |
}() | |
} | |
func writeLogs() { | |
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 LogRequest(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