-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
95 lines (81 loc) · 1.85 KB
/
log.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
package cmd
import (
"log"
"os"
"path/filepath"
)
const (
loggingLevelNone = iota
loggingLevelDebug
loggingLevelInfo
loggingLevelWarn
loggingLevelError
)
var (
loggingLevel = loggingLevelNone
loggingFile *os.File
)
// log writes message to the log
func writeLog(level int, prefix string, v ...interface{}) {
if level < loggingLevel {
return
}
v = append([]interface{}{prefix}, v...)
log.Println(v...)
}
// logDebug logs a debugging message
func logDebug(v ...interface{}) {
writeLog(loggingLevelDebug, "DEBUG:", v...)
}
// logInfo logs an info message
func logInfo(v ...interface{}) {
writeLog(loggingLevelInfo, "INFO:", v...)
}
// logWarn logs a warning message
func logWarn(v ...interface{}) {
writeLog(loggingLevelWarn, "WARN:", v...)
}
// logError logs an error message
func logError(v ...interface{}) {
writeLog(loggingLevelError, "ERROR:", v...)
}
// logFatal logs an error message and terminates the program
func logFatal(v ...interface{}) {
logError(v...)
os.Exit(1)
}
// getLogLevel converts level to a log level int value
func getLogLevel(level string) int {
// logging levels: debug, info, warn, error
switch level {
case "debug":
return loggingLevelDebug
case "info":
return loggingLevelInfo
case "warn":
return loggingLevelWarn
case "error":
return loggingLevelError
default:
return loggingLevelNone
}
}
// stopLogging stops looging to the log file
func stopLogging() {
log.SetOutput(os.Stderr)
loggingFile.Close()
}
// initLogging initializes logging to the log file
func initLogging() {
// set loglevel from config
loggingLevel = getLogLevel(conf.Loglevel)
// create/open log file
file := filepath.Join(conf.Dir, conf.Name+".log")
f, err := os.OpenFile(file, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
log.Fatal(err)
}
loggingFile = f
// set logging output to logfile
log.SetOutput(loggingFile)
}