-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
81 lines (73 loc) · 1.81 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
package logger
import (
"fmt"
"io"
"log"
)
// ANSI escape codes for text formatting
const (
Reset = "\033[0m"
Red = "\033[91m"
Yellow = "\033[93m"
Green = "\033[92m"
Purple = "\033[94m"
BgRed = "\033[41m"
BgPurple = "\033[44m"
)
type LoggerConfig struct {
WriteTo io.Writer
LogLevel LogLevel
WithDateTime bool
}
func applyFormat(color string, flag string) string {
return fmt.Sprintf("%s[%s]%s ", color, flag, Reset)
}
func New(c LoggerConfig) (*Logger, error) {
var wr io.Writer = c.WriteTo
var flag int
if c.WithDateTime == true {
flag = log.LUTC | log.Ldate | log.Ltime | log.Lshortfile
}
DebugLogger := log.New(wr, applyFormat(Purple, "DEBUG"), flag)
InfoLogger := log.New(wr, applyFormat(Green, "INFO"), flag)
WarningLogger := log.New(wr, applyFormat(Yellow, "WARN"), flag)
ErrorLogger := log.New(wr, applyFormat(Red, "ERROR"), flag)
CriticalLogger := log.New(wr, applyFormat(BgRed, "CRITICAL"), flag)
if c.LogLevel > DebugLevel {
DebugLogger = log.New(io.Discard, "", flag)
}
if c.LogLevel > InfoLevel {
InfoLogger = log.New(io.Discard, "", flag)
}
if c.LogLevel > WarningLevel {
WarningLogger = log.New(io.Discard, "", flag)
}
if c.LogLevel > ErrorLevel {
ErrorLogger = log.New(io.Discard, "", flag)
}
if c.LogLevel > CriticalLevel {
CriticalLogger = log.New(io.Discard, "", flag)
}
logger := &Logger{}
logger.Debug = DebugLogger.Println
logger.Info = InfoLogger.Println
logger.Warning = WarningLogger.Println
logger.Error = ErrorLogger.Println
logger.Critical = CriticalLogger.Println
return logger, nil
}
type LogLevel int
const (
DebugLevel LogLevel = iota
InfoLevel
WarningLevel
ErrorLevel
CriticalLevel
)
type Logger struct {
Error func(v ...any)
Critical func(v ...any)
Debug func(v ...any)
Info func(v ...any)
Warning func(v ...any)
}