-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathlogger.go
114 lines (97 loc) · 2.49 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package main
import (
"fmt"
"log"
"os"
"strings"
"github.com/acarl005/stripansi"
"github.com/fatih/color"
)
type Logger struct {
Error func(string, ...interface{})
Warn func(string, ...interface{})
Info func(string, ...interface{})
Succ func(string, ...interface{})
}
// global error logger variables
var (
logFile *os.File
logger *log.Logger
Log = Logger{
Error: logError,
Warn: logWarn,
Info: logInfo,
Succ: logSuccess,
}
)
// error logger function
func logError(logText string, vars ...interface{}) {
logEntry("error", logText, vars...)
}
func logWarn(logText string, vars ...interface{}) {
logEntry("warn", logText, vars...)
}
func logInfo(logText string, vars ...interface{}) {
logEntry("info", logText, vars...)
}
func logSuccess(logText string, vars ...interface{}) {
logEntry("success", logText, vars...)
}
func logEntry(logType string, logText string, vars ...interface{}) {
// init logger if nil
if args.Debug && logFile == nil {
initLogger(logFilePath)
}
// log error
if logType == "error" {
if args.Debug {
logger.Printf("ERROR: %s\n", stripansi.Strip(strings.Trim(fmt.Sprintf(logText, vars...), "\n")))
}
color.Set(color.FgRed)
fmt.Printf(" ERROR: %s\n", fmt.Sprintf(logText, vars...))
color.Unset()
}
// log warn
if logType == "warn" {
if args.Debug {
logger.Printf("WARNING: %s\n", stripansi.Strip(strings.Trim(fmt.Sprintf(logText, vars...), "\n")))
}
color.Set(color.FgYellow)
fmt.Printf(" WARNING: %s\n", fmt.Sprintf(logText, vars...))
color.Unset()
}
// log info
if logType == "info" {
if args.Debug {
logger.Printf("INFO: %s\n", stripansi.Strip(strings.Trim(fmt.Sprintf(logText, vars...), "\n")))
}
fmt.Printf(" %s\n", fmt.Sprintf(logText, vars...))
}
// log success
if logType == "success" {
if args.Debug {
logger.Printf("SUCCESS: %s\n", stripansi.Strip(strings.Trim(fmt.Sprintf(logText, vars...), "\n")))
}
color.Set(color.FgGreen)
fmt.Printf(" SUCCESS: %s\n", fmt.Sprintf(logText, vars...))
color.Unset()
}
}
func initLogger(file string) {
var err error
if logFile, err = os.OpenFile(file, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666); err == nil {
logger = log.New(logFile, "", log.Ldate|log.Ltime)
logger.Printf("INFO: %s %s started", appName, appVersion)
} else {
color.Set(color.FgRed)
fmt.Printf(" ERROR: Fatal error while opening log file '%s': %s\n", file, err.Error())
color.Unset()
exit(1)
}
}
func logClose() {
// clean up
if logFile != nil {
logFile.Close()
}
}