forked from hbollon/IGopher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
89 lines (77 loc) · 1.92 KB
/
logger.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
package igopher
import (
"bufio"
"os"
"runtime"
logRuntime "github.com/banzaicloud/logrus-runtime-formatter"
"github.com/rifflock/lfshook"
"github.com/shiena/ansicolor"
"github.com/sirupsen/logrus"
log "github.com/sirupsen/logrus"
)
const logFilePath = "./logs/logs.log"
func InitLogger() {
setLoggerOutput()
level, err := log.ParseLevel(*Flags.LogLevelFlag)
if err == nil {
log.SetLevel(level)
} else {
log.SetLevel(log.InfoLevel)
log.Warnf("Invalid log level '%s', use default one.", *Flags.LogLevelFlag)
}
}
func setLoggerOutput() {
// Initialize logs folder
if _, err := os.Stat("./logs/"); os.IsNotExist(err) {
os.Mkdir("./logs/", os.ModePerm)
}
// Add formatter to logrus in order to display line and function with messages on Stdout
formatter := logRuntime.Formatter{ChildFormatter: &log.TextFormatter{
FullTimestamp: false,
ForceColors: true,
}}
formatter.Line = true
log.SetFormatter(&formatter)
if runtime.GOOS == "windows" {
log.SetOutput(ansicolor.NewAnsiColorWriter(os.Stdout))
} else {
log.SetOutput(os.Stdout)
}
// Add hook to logrus to also redirect logs to files with custom formatter
log.AddHook(lfshook.NewHook(
lfshook.PathMap{
logrus.InfoLevel: logFilePath,
logrus.WarnLevel: logFilePath,
logrus.ErrorLevel: logFilePath,
logrus.FatalLevel: logFilePath,
},
&logrus.JSONFormatter{},
))
}
// Read and parse log file to json array string
func parseLogsToString() (string, error) {
// Open log file
file, err := os.Open(logFilePath)
if err != nil {
return "", err
}
defer file.Close()
// Parse logs to string array
var logs []string
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
logs = append(logs, scanner.Text())
}
// Build json array string with logs from newer to older
out := `[`
for i := len(logs) - 1; i >= 0; i-- {
out += logs[i]
if i == 0 {
break
}
out += `,`
}
out += `]`
return out, nil
}