-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror_logging.go
More file actions
180 lines (153 loc) · 3.58 KB
/
error_logging.go
File metadata and controls
180 lines (153 loc) · 3.58 KB
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
package logging
import (
"context"
"fmt"
"io"
"log"
"path"
"runtime"
"strings"
"time"
)
func LogError(ctx context.Context, err error, errorLogger *log.Logger) {
if err == nil {
return
}
file := "unknown"
line := 0
if _, f, l, ok := runtime.Caller(2); ok {
file = path.Base(f)
line = l
}
meta, ok := FromContext(ctx)
if ok {
ts := time.Now().Format("15:04:05")
sep := fmt.Sprintf(
"==============================CRITICAL[%s]==================================",
ts,
)
errorLogger.Printf("[%s]", "ERROR")
printRaw(errorLogger, sep)
printRaw(
errorLogger,
fmt.Sprintf(
`ERROR : %v
REQ : %s
FROM : %s:%d
HTTP : %s %s (%s)
UA : %s
STACK :
%s`,
err,
meta.RequestID,
path.Base(file),
line,
meta.Method,
meta.Path,
meta.IP,
meta.UserAgent,
prettyStackList(3, 6),
),
)
printRaw(errorLogger, "\n"+sep)
return
}
errorLogger.Printf(
"[CRITICAL] err=%v",
err,
)
}
func printRaw(l *log.Logger, s string) {
oldFlags := l.Flags()
l.SetFlags(0)
l.Println(s)
l.SetFlags(oldFlags)
}
func prettyStackList(skip, max int) string {
var b strings.Builder
for i := skip; i < skip+max; i++ {
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
fn := runtime.FuncForPC(pc)
name := "unknown"
if fn != nil {
name = path.Base(fn.Name())
}
b.WriteString(fmt.Sprintf(
"- %-28s %s\n",
fmt.Sprintf("%s:%d", path.Base(file), line),
name,
))
}
return strings.TrimRight(b.String(), "\n")
}
func LogErrorLoki(ctx context.Context, service string, level string, err error, writer io.Writer) {
LogLoki(ctx, service, level, 500, 0, err, writer)
}
func stackFrames(skip, max int) []string {
var frames []string
for i := skip; i < skip+max; i++ {
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
fn := runtime.FuncForPC(pc)
name := "unknown"
if fn != nil {
name = path.Base(fn.Name())
}
frames = append(
frames,
fmt.Sprintf("%s:%d %s", path.Base(file), line, name),
)
}
return frames
}
func LogAccessLoki(ctx context.Context, service string, level string, statusCode int, latency time.Duration, writer io.Writer) {
LogLoki(ctx, service, level, statusCode, latency, nil, writer)
}
/**
* LogLoki logs in unified JSON format suitable for Loki/Grafana integration.
* Format is consistent regardless of success/error - errors field is null on success.
*
* @param ctx Context containing request metadata
* @param service Service name for identification
* @param level Log level (INFO, WARN, ERROR, CRITICAL)
* @param statusCode HTTP response status code
* @param latency Request processing duration
* @param err Optional error (null in output if nil)
* @param writer Output writer for log entry
*/
func LogLoki(ctx context.Context, service string, level string, statusCode int, latency time.Duration, err error, writer io.Writer) {
meta, _ := FromContext(ctx)
ev := map[string]interface{}{
"ts": time.Now().Format(time.RFC3339),
"level": strings.ToUpper(level),
"service": service,
"request_id": meta.RequestID,
"status_code": statusCode,
"latency_ms": latency.Milliseconds(),
"http": map[string]string{
"method": meta.Method,
"path": meta.Path,
"ip": meta.IP,
"ua": meta.UserAgent,
},
"errors": nil,
}
if err != nil {
_, file, line, _ := runtime.Caller(3)
ev["errors"] = map[string]interface{}{
"error": err.Error(),
"source": map[string]interface{}{
"file": path.Base(file),
"line": line,
},
"stack": stackFrames(4, 6),
}
}
b, _ := jsonMarshal(ev)
writer.Write(append(b, '\n'))
}