-
Notifications
You must be signed in to change notification settings - Fork 2
/
logger.go
93 lines (79 loc) · 2.2 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
//Package logger implements logging methods with formatted output
//and more detailed logging information than provided in the standard
//logging package of golang. It is possible to specify the level of
//logging information to be written as output (Default: all information is written).
//Use the `*log.Logger` variables and chain them to common I/O writers
// for printing logging information.
package logger
import (
"fmt"
"io"
"log"
"os"
)
//LogLevel indicates the level of logging information passed as
//argument to SetLevel function.
type LogLevel int
//There are four possible values for type `LogLevel`:
//
// 1. `LEVEL_ERROR`: Only Error logs are written to `stderr`.
//
// 2. `LEVEL_WARNING`: Warnings and errors are written to `stderr`.
//
// 3. `LEVEL_INFO`: Errors and warnings are written to `stderr`, infos to `stdout`.
//
// 4. `LEVEL_DEBUG`: Errors and warnings are written to `stderr`, infos and debugs to `stdout`.
const (
LEVEL_ERROR LogLevel = iota
LEVEL_WARNING
LEVEL_INFO
LEVEL_DEBUG
)
var Error = getErrorLogger()
var Warning = getWarningLogger()
var Info = getInfoLogger()
var Debug = getDebugLogger()
//SetLevel sets the level of logging information written as output.
func SetLevel(level LogLevel) {
Error = getErrorLogger()
Warning = getWarningLogger()
Info = getInfoLogger()
Debug = getDebugLogger()
switch level {
case LEVEL_ERROR:
Warning = getEmptyLogger()
Info = getEmptyLogger()
Debug = getEmptyLogger()
case LEVEL_WARNING:
Info = getEmptyLogger()
Debug = getEmptyLogger()
case LEVEL_INFO:
Debug = getEmptyLogger()
case LEVEL_DEBUG:
return
}
}
func getErrorLogger() *log.Logger {
return getLogger("ERROR", true)
}
func getWarningLogger() *log.Logger {
return getLogger("WARNING", true)
}
func getInfoLogger() *log.Logger {
return getLogger("INFO", false)
}
func getDebugLogger() *log.Logger {
return getLogger("DEBUG", false)
}
func getLogger(prefix string, error bool) *log.Logger {
var writer io.Writer
if error {
writer = os.Stderr
} else {
writer = os.Stdout
}
return log.New(writer, fmt.Sprintf("[%s]: ", prefix), log.Ldate|log.Ltime|log.Lshortfile|log.Lmsgprefix)
}
func getEmptyLogger() *log.Logger {
return log.New(emptyWriter{}, "", 0)
}