-
Notifications
You must be signed in to change notification settings - Fork 7
/
logger.go
101 lines (85 loc) · 2.51 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
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"strings"
color "github.com/TwiN/go-color"
"github.com/acarl005/stripansi"
)
type Logger struct {
Error func(string, ...interface{})
Warn func(string, ...interface{})
Info func(string, ...interface{})
Succ func(string, ...interface{})
}
// global error logger variables
var (
logFileName = "./logfile.txt"
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 == true && logFile == nil {
initLogger(filepath.Join(appPath, logFileName))
}
// log error
if logType == "error" {
if args.Debug == true {
logger.Printf("ERROR: %s\n", stripansi.Strip(strings.Trim(fmt.Sprintf(logText, vars...), "\n")))
}
fmt.Printf(" %sERROR: %s%s\n", color.Red, fmt.Sprintf(logText, vars...), color.Reset)
}
// log warn
if logType == "warn" {
if args.Debug == true {
logger.Printf("WARNING: %s\n", stripansi.Strip(strings.Trim(fmt.Sprintf(logText, vars...), "\n")))
}
fmt.Printf(" %sWARNING: %s%s\n", color.Yellow, fmt.Sprintf(logText, vars...), color.Reset)
}
// log info
if logType == "info" {
if args.Debug == true {
logger.Printf("INFO: %s\n", stripansi.Strip(strings.Trim(fmt.Sprintf(logText, vars...), "\n")))
}
fmt.Printf(" %s%s%s\n", color.Reset, fmt.Sprintf(logText, vars...), color.Reset)
}
// log success
if logType == "success" {
if args.Debug == true {
logger.Printf("INFO: %s\n", stripansi.Strip(strings.Trim(fmt.Sprintf(logText, vars...), "\n")))
}
fmt.Printf(" %s%s%s\n", color.Green, fmt.Sprintf(logText, vars...), color.Reset)
}
}
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 {
fmt.Printf(" %sERROR: Fatal error while opening log file '%s': %s%s\n", color.Red, file, err.Error(), color.Reset)
exit(1)
}
}