-
Notifications
You must be signed in to change notification settings - Fork 1
/
offline.go
106 lines (86 loc) · 2.2 KB
/
offline.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package logpet
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
func (l *StandardLogger) EnableOfflineLogs(enable bool) {
l.saveOfflineLogs = enable
}
func (l *StandardLogger) saveLogToFile(toSave []byte, filename string) error {
_, err := os.Stat(l.offlineLogsPath)
if os.IsNotExist(err) {
err = os.Mkdir(l.offlineLogsPath, 0644)
if err != nil {
return err
}
}
filename = strings.ReplaceAll(filename, ":", "-")
filename = filepath.Join(l.offlineLogsPath, filename)
_, err = os.Stat(filename)
if os.IsNotExist(err) {
_, err := os.Create(filename)
if err != nil {
return err
}
}
err = ioutil.WriteFile(filename, toSave, 0644)
if err != nil {
return err
}
return nil
}
func (l *StandardLogger) SendOfflineLogs() error {
dir, err := ioutil.ReadDir(l.offlineLogsPath)
if err != nil {
return errors.New(fmt.Sprintf("unable to open directory %s, %v", l.offlineLogsPath, err))
}
for _, logfile := range dir {
if strings.HasPrefix(logfile.Name(), "log-") {
filename := filepath.Join(l.offlineLogsPath, logfile.Name())
// read and send
file, err := os.Open(filename)
if err != nil {
l.SendErrfLog("unable to open file %s", nil, logfile.Name())
continue
}
var logs ClientLog
err = json.NewDecoder(file).Decode(&logs)
if err != nil {
l.SendErrfLog("error decoding json log %s, due to %v", nil, file.Name(), err)
// Close file and handle err
err = file.Close()
if err != nil {
l.SendErrfLog("error closing json log %s, due to %v", nil, file.Name(), err)
}
continue
}
switch logs.Level {
case "info":
l.SendInfoLog(logs.Message, nil)
case "warning":
l.SendWarnLog(logs.Message, nil)
case "error":
l.SendErrLog(logs.Message, nil)
case "debug":
l.SendDebugLog(logs.Message, nil)
case "fatal":
l.SendErrfLog("EX FATAL | %s", nil, logs.Message)
}
// Close file and handle err
err = file.Close()
if err != nil {
l.SendErrfLog("unable to close file %s due to %v", nil, file.Name(), err)
}
err = os.Remove(filename)
if err != nil {
l.SendErrfLog("unable to remove file %s due to %v", nil, file.Name(), err)
}
}
}
return nil
}