-
Notifications
You must be signed in to change notification settings - Fork 0
/
prettyLogger.go
222 lines (201 loc) · 5.53 KB
/
prettyLogger.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
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package PrettyLogger
import (
"fmt"
errs "github.com/pkg/errors"
"github.com/sirupsen/logrus"
"log/slog"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"time"
)
var cf *ColoredFormatter = &ColoredFormatter{TimestampFormat: time.RFC3339, LogLevel: "info"}
func SetUpLogrusAndSlog(logLevel string) {
cf = &ColoredFormatter{TimestampFormat: time.RFC3339, LogLevel: logLevel}
logrus.SetFormatter(cf)
logrus.SetOutput(os.Stdout)
logrus.SetLevel(ConvertLogLevel(logLevel))
// integrate Logrus with the slog logger
slog.SetDefault(slog.New(NewLogrusHandler(logrus.StandardLogger())))
}
// logErrorWithStack logs an Error with a stack trace.
func getLocation(skip int) (file string) {
if _, filename, line, ok := runtime.Caller(skip); !ok {
fmt.Println("failed to get caller")
return
} else if workingDir, e1 := os.Getwd(); e1 != nil {
fmt.Println(e1)
return
} else if relativePath, e2 := filepath.Rel(workingDir, filename); e2 != nil {
fmt.Println(e2)
return
} else {
return fmt.Sprintf("%s:%d", relativePath, line)
}
}
func getRelativePath(absPath string) string {
absPath = strings.TrimSpace(absPath)
if strings.Contains(absPath, ":") {
i := strings.LastIndex(absPath, ":")
path := absPath[:i]
line := absPath[i+1:]
if workingDir, e1 := os.Getwd(); e1 != nil {
return absPath
} else if relativePath, e2 := filepath.Rel(workingDir, path); e2 != nil {
return absPath
} else {
return relativePath + ":" + line
}
} else {
return ""
}
}
func parseWrappedError(str string) string {
stack := ""
spl := strings.Split(str, "\n---\n")
for _, s := range spl {
lines := strings.Split(strings.TrimSpace(s), "\n")
msg := lines[0]
if strings.Contains(msg, "file=\"") {
file := strings.Split(" "+msg, "file=\"")[1]
if strings.Contains(file, "\" msg=\"") {
message := strings.TrimSuffix(strings.Split(" "+file, "\" msg=\"")[1], "\"")
file = strings.TrimSuffix(strings.Split(file, "\" msg=\"")[0], "\"")
gotit := false
if len(lines) >= 2 {
for _, line := range lines[1:] {
if strings.Contains(line, file) {
stack = stack + fmt.Sprintf("\t\t\t\t → %s %s\n", getRelativePath(line), message)
gotit = true
break
}
}
}
if !gotit {
stack = stack + fmt.Sprintf("\t\t\t\t → %s %s\n", getRelativePath(file), message)
}
}
} else {
message := lines[0]
if len(lines) < 3 {
if len(lines) == 2 {
file := lines[1]
stack = stack + fmt.Sprintf("\t\t\t\t → %s %s\n", getRelativePath(file), message)
} else if len(lines) == 1 {
//file := lines[0]
file := getRelativePath(lines[0])
if file == "" {
stack = stack + fmt.Sprintf("\t\t\t\t → %s\n", message)
} else {
stack = stack + fmt.Sprintf("\t\t\t\t → %s %s\n", file, message)
}
} else {
stack = stack + fmt.Sprintf("\t\t\t\t → %s\n", message)
}
} else {
file := lines[2]
stack = stack + fmt.Sprintf("\t\t\t\t → %s %s\n", getRelativePath(file), message)
}
}
}
return stack
}
func WrapError(err error, format string, a ...any) error {
if err == nil {
return withStackSkip(fmt.Errorf(format, a...), 2)
}
msg := fmt.Sprintf(format, a...)
file := getLocation(2)
return errs.Wrap(err, fmt.Sprintf("\n---\nfile=\"%s\" msg=\"%s\"", file, msg))
}
type stackTracer interface {
StackTrace() errs.StackTrace
}
func LogNewError(format string, a ...any) {
slog.Error("", withStackSkip(fmt.Errorf(format, a...), 2))
}
func NewError(format string, a ...any) error {
err := fmt.Errorf(format, a...)
return withStackSkip(err, 1)
}
func withStackSkip(err error, skip int) error {
if err == nil {
return nil
}
pcs := make([]uintptr, 32)
n := runtime.Callers(skip+2, pcs)
pcs = pcs[:n]
return &withStack{
error: err,
stack: pcs,
}
}
func interfaceToString(field interface{}) string {
paramStr := ""
if field == nil {
paramStr = "nil"
} else {
paramValue := reflect.ValueOf(field)
paramType := reflect.TypeOf(field)
if paramType.Kind() == reflect.String {
paramStr = fmt.Sprintf("%s", paramValue.Interface())
} else {
val := reflect.ValueOf(paramValue.Interface())
// Check if the value is a pointer, and get the element it points to
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
// Ensure the value is a struct
if val.Kind() == reflect.Struct {
typ := val.Type()
members := make([]string, 0)
for j := 0; j < val.NumField(); j++ {
inter := val.Field(j)
if inter.CanInterface() {
value := interfaceToString(inter.Interface())
members = append(members, fmt.Sprintf("%s:%v", cf.Italic(cf.ColorGrey(typ.Field(j).Name)), value))
}
}
paramStr = fmt.Sprintf("%s{%s}", cf.ColorGrey(typ.Name()), strings.Join(members, ", "))
} else {
paramStr = fmt.Sprintf("%v", paramValue.Interface())
}
}
}
return paramStr
}
type withStack struct {
error
stack []uintptr
}
func (w *withStack) StackTrace() errs.StackTrace {
frames := make([]errs.Frame, len(w.stack))
for i := range frames {
frames[i] = errs.Frame(w.stack[i])
}
return frames
}
func (w *withStack) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
fmt.Fprintf(s, "%+v", w.error)
for _, pc := range w.stack {
f := errs.Frame(pc)
fmt.Fprintf(s, "\n%+v", f)
}
return
}
fallthrough
case 's':
fmt.Fprint(s, w.error.Error())
case 'q':
fmt.Fprintf(s, "%q", w.error.Error())
}
}
func wrapError(err error, msg string) error {
file := getLocation(5)
return errs.Wrap(err, fmt.Sprintf("\n---\nfile=\"%s\" msg=\"%s\"", file, msg))
}