aboutsummaryrefslogtreecommitdiff
path: root/utils/logger/logger.go
blob: 9fc1bc7ec6239cdd3d7ef5b2a417998abc3b514e (plain)
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package logger

import (
	"fmt"
	"os"
	"strings"
	"time"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

const prefixWidth = 15

var (
	loggerInstance *zap.Logger
	level          zap.AtomicLevel
	showTimestamp  bool
)

func timeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
	enc.AppendString(Gray + t.Format(time.RFC3339) + Reset)
}

func levelEncoder(l zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
	switch l {
	case zapcore.DebugLevel:
		enc.AppendString(LevelColorDebug)
	case zapcore.WarnLevel:
		enc.AppendString(LevelColorWarn)
	case zapcore.ErrorLevel:
		enc.AppendString(LevelColorError)
	default:
		enc.AppendString(LevelColorInfo)
	}
}

func formatPrefix(prefix string) string {
	if prefix == "" {
		return ""
	}

	padding := ""
	if len(prefix) < prefixWidth {
		padding = strings.Repeat(" ", prefixWidth-len(prefix))
	}

	return Cyan + "[" + prefix + "]" + Reset + padding
}

func colorMessage(level LogLevel, msg string) string {
	switch level {
	case Debug:
		return MessageColorDebug + msg + Reset
	case Warn:
		return MessageColorWarn + msg + Reset
	case Error:
		return MessageColorError + msg + Reset
	case Success:
		return MessageColorSuccess + msg + Reset
	default:
		return MessageColorInfo + msg + Reset
	}
}

func Init() {
	level = zap.NewAtomicLevelAt(zapcore.InfoLevel)

	encoderCfg := zapcore.EncoderConfig{
		LevelKey:    "level",
		MessageKey:  "msg",
		LineEnding:  "\n",
		EncodeLevel: levelEncoder,
	}

	if showTimestamp {
		encoderCfg.TimeKey = "ts"
		encoderCfg.EncodeTime = timeEncoder
	}

	encoder := zapcore.NewConsoleEncoder(encoderCfg)

	stdout := zapcore.AddSync(os.Stdout)
	stderr := zapcore.AddSync(os.Stderr)

	core := zapcore.NewTee(
		zapcore.NewCore(encoder, stdout, zap.LevelEnablerFunc(func(l zapcore.Level) bool {
			return l < zapcore.WarnLevel && level.Enabled(l)
		})),
		zapcore.NewCore(encoder, stderr, zap.LevelEnablerFunc(func(l zapcore.Level) bool {
			return l >= zapcore.WarnLevel && level.Enabled(l)
		})),
	)

	loggerInstance = zap.New(core, zap.AddCaller())
}

func SetTimestamp(enabled bool) {
	showTimestamp = enabled
}

func SetDebug(enabled bool) {
	if enabled {
		level.SetLevel(zapcore.DebugLevel)
	} else {
		level.SetLevel(zapcore.InfoLevel)
	}
}

func Debugf(prefix, format string, args ...any) {
	log(Debug, zapcore.DebugLevel, prefix, fmt.Sprintf(format, args...))
}

func Infof(prefix, format string, args ...any) {
	log(Info, zapcore.InfoLevel, prefix, fmt.Sprintf(format, args...))
}

func Successf(prefix, format string, args ...any) {
	log(Success, zapcore.InfoLevel, prefix, fmt.Sprintf(format, args...))
}

func Warnf(prefix, format string, args ...any) {
	log(Warn, zapcore.WarnLevel, prefix, fmt.Sprintf(format, args...))
}

func Errorf(prefix, format string, args ...any) {
	log(Error, zapcore.ErrorLevel, prefix, fmt.Sprintf(format, args...))
}

func Fatalf(prefix, format string, args ...any) {
	log(Error, zapcore.ErrorLevel, prefix, fmt.Sprintf(format, args...))
	os.Exit(1)
}

func log(levelLabel LogLevel, zapLevel zapcore.Level, prefix string, msg any) {
	if loggerInstance == nil {
		panic("logger.Init() was not called")
	}

	message := fmt.Sprint(msg)
	colored := colorMessage(levelLabel, message)
	fullMessage := formatPrefix(prefix) + colored

	loggerInstance.Log(zapLevel, fullMessage)
}