Created
January 2, 2022 19:37
-
-
Save erayakartuna/102da91f8efc1351b44ffd52bc9c7768 to your computer and use it in GitHub Desktop.
Logv2
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 { | |
responses []string | |
sync.Mutex | |
} | |
var logs RequestLogs | |
// InitRequestLogs ... | |
func InitRequestLogs() { | |
go func() { | |
for { | |
time.Sleep(time.Second * 5) | |
writeLogs() | |
} | |
}() | |
} | |
func SaveRequest(url string, reqBody string, respStatus int, resp string) { | |
r := fmt.Sprintf( | |
`{"url": "%s", "reqBody": "%s", "respStatus": "%d", "resp": "%s"\n\r`, | |
jsonEscape(url), | |
jsonEscape(reqBody), | |
respStatus, | |
jsonEscape(resp), | |
) | |
logs.Lock() | |
logs.responses = append(logs.responses, r) | |
logs.Unlock() | |
} | |
func writeLogs() { | |
logs.Lock() | |
tmp := append(logs.responses[:0:0], logs.responses...) | |
logs.responses = nil | |
logs.Unlock() | |
file := new(bytes.Buffer) | |
for _, v := range tmp { | |
if _, err := file.WriteString(v); err != nil { | |
return err | |
} | |
} | |
// it can be any storage | |
s := storage.New() | |
s.Write(fmt.Sprintf("%s.json", time.Now().String()), file.Bytes(), "text/json") | |
} | |
// 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