generated from gleich/go_template
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlog.go
103 lines (87 loc) · 2.42 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
96
97
98
99
100
101
102
103
package lumber
import (
"fmt"
"io"
"log"
"os"
"strings"
"time"
"github.com/charmbracelet/lipgloss"
"github.com/pkg/errors"
)
type logLevel string
const (
debugLevel logLevel = "DEBUG"
doneLevel logLevel = "DONE "
infoLevel logLevel = "INFO "
warningLevel logLevel = "WARN "
errorLevel logLevel = "ERROR"
fatalLevel logLevel = "FATAL"
)
func format(level logLevel, color lipgloss.Style, v ...any) string {
var joined strings.Builder
for i, item := range v {
if i > 0 {
joined.WriteString(" ")
}
fmt.Fprint(&joined, item)
}
return fmt.Sprintf(
"%s %s %s",
time.Now().In(logger.timezone).Format(logger.timeFormat),
color.Render(string(level)),
strings.TrimPrefix(joined.String(), " "),
)
}
// Normal log output
func logNormal(level logLevel, color lipgloss.Style, v ...any) {
logger.mutex.RLock()
defer logger.mutex.RUnlock()
out := format(level, color, v...)
log.New(io.MultiWriter(append(logger.extraNormalOuts, logger.normalOut)...), "", 0).Println(out)
}
func logError(err error, level logLevel, color lipgloss.Style, v ...any) {
logger.mutex.RLock()
defer logger.mutex.RUnlock()
out := format(level, color, v...)
if err != nil && logger.showStack {
out += fmt.Sprintf("\n%+v", errors.WithStack(err))
} else if err != nil {
out += fmt.Sprintf("\n%s", err)
}
log.New(io.MultiWriter(append(logger.extraErrOuts, logger.errOut)...), "", 0).Println(out)
}
// Output a INFO log message
func Debug(v ...any) {
logNormal(debugLevel, logger.colors.DebugStyle, v...)
}
// Output a DONE log message
func Done(v ...any) {
logNormal(doneLevel, logger.colors.DoneStyle, v...)
}
// Output a INFO log message
func Info(v ...any) {
logNormal(infoLevel, logger.colors.InfoStyle, v...)
}
// Output a WARN log message
func Warning(v ...any) {
logNormal(warningLevel, logger.colors.WarningStyle, v...)
}
// Output a ERROR log message with information about the error
func Error(err error, v ...any) {
logError(err, errorLevel, logger.colors.ErrorStyle, v...)
}
// Output a ERROR log message
func ErrorMsg(v ...any) {
logError(nil, errorLevel, logger.colors.ErrorStyle, v...)
}
// Output a FATAL log message with information about the error
func Fatal(err error, v ...any) {
logError(err, fatalLevel, logger.colors.FatalStyle, v...)
os.Exit(logger.fatalExitCode)
}
// Output a FATAL log message
func FatalMsg(v ...any) {
logError(nil, fatalLevel, logger.colors.FatalStyle, v...)
os.Exit(logger.fatalExitCode)
}