-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
208 lines (183 loc) · 4.81 KB
/
main.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
package main
import (
"context"
"database/sql"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"time"
"github.com/vovanec/serror"
"github.com/vovanec/serror/loghelper"
)
type AppVersion struct {
Major int
Minor int
Patch int
}
func (v AppVersion) LogValue() slog.Value {
return slog.GroupValue(
slog.Int("major", v.Major),
slog.Int("minor", v.Minor),
slog.Int("patch", v.Patch),
)
}
type Application struct {
Name string
Version AppVersion
Build string
}
func (a Application) LogValue() slog.Value {
return slog.GroupValue(
slog.String("name", a.Name),
slog.Any("version", a.Version),
slog.Group("build",
slog.String("hash", a.Build),
),
)
}
func dbGetUser(ctx context.Context, _ string) error {
/* This will dump the JSON log similar to below object, with log attributes provided by the caller in a context:
{
"time": "2023-11-24T20:39:57.203458-06:00",
"level": "INFO",
"msg": "getting user from the database",
"application": {
"name": "vovan",
"version": {
"major": 1,
"minor": 7,
"patch": 2
},
"build": {
"hash": "20b8c3f"
}
},
"request": {
"id": "b4133182-89a6-11ee-b9d1-0242ac120002"
},
"user": {
"id": "8b50d0c8-015a-497c-b98a-cc69fec2f9ed"
}
}
*/
slog.Info("getting user from the database",
loghelper.Attr(ctx))
// code to get user data from the database
return serror.Wrap(sql.ErrNoRows, "error getting user from database",
// Log attributes can be attached to the error, they will be logged by the caller.
loghelper.Attr(
slog.Group("db",
slog.String("query", "SELECT first_name, last_name FROM users WHERE id=$1"),
),
),
)
}
func handleGetUser(ctx context.Context, userId string) error {
if err := dbGetUser(ctx, userId); err != nil {
// Error can be wrapped multiple times and additional log attributes can be attached.
return serror.Wrap(err, "error in handleGetUser",
// Log attributes can be attached to the error, they will be logged by the caller.
loghelper.Attr(
slog.Any("execution_time", time.Now()),
),
)
}
return nil
}
func (a Application) HandleRequest(w http.ResponseWriter, r *http.Request) {
// Add application information to the context. Application instance can be directly passed to
// slog.Any since it implements slog.LogValuer interface.
ctx := loghelper.Context(r.Context(),
slog.Any("application", a),
)
var (
requestId = r.Header.Get("x-request-id")
userId = r.URL.Query().Get("id")
)
// Some request-scope data can be extracted from the request and added
// to the context, so it can be passed to the callee and logged.
ctx = loghelper.Context(ctx,
slog.Group("request",
slog.String("id", requestId),
),
slog.Group("user",
slog.String("id", userId),
),
)
// context.Context contains application info, user id and request id they can be logged by the callee with minimal effort.
if err := handleGetUser(ctx, userId); err != nil {
/* This will dump the JSON log similar to below object:
{
"time": "2023-11-24T20:31:58.408805-06:00",
"level": "ERROR",
"msg": "error occurred",
"application": { <<- from the context
"name": "vovan",
"version": {
"major": 1,
"minor": 7,
"patch": 2
},
"build": {
"hash": "20b8c3f"
}
},
"request": { <<- from the context
"id": "b4133182-89a6-11ee-b9d1-0242ac120002"
},
"user": { <<- from the context
"id": "8b50d0c8-015a-497c-b98a-cc69fec2f9ed"
}
"db": { <<- from dbGetUser
"query": "SELECT first_name, last_name FROM users WHERE id=$1"
},
"error": {
"msg": "error in handleGetUser: error getting user from database: sql: no rows in result set",
"origin": "/Users/vovan/work/errors/example/main.go:55"
},
"execution_time": "2023-11-24T20:31:58.408777-06:00", <<- handleGetUser
}
*/
slog.Error("error occurred",
loghelper.Attr(ctx, err),
)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(http.StatusText(http.StatusInternalServerError)))
return
}
w.Write(nil)
}
func main() {
loghelper.InitLogging(
loghelper.WithLevel(slog.LevelDebug),
loghelper.WithOutput(os.Stderr),
)
var (
app = Application{
Name: "vovan",
Build: "20b8c3f",
Version: AppVersion{
Major: 1,
Minor: 7,
Patch: 2,
},
}
req = httptest.NewRequest(
http.MethodGet,
"/user?id=8b50d0c8-015a-497c-b98a-cc69fec2f9ed",
nil)
w = httptest.NewRecorder()
)
req.Header.Set("x-request-id", "b4133182-89a6-11ee-b9d1-0242ac120002")
app.HandleRequest(w, req)
res := w.Result()
defer res.Body.Close()
if data, err := io.ReadAll(res.Body); err != nil {
panic(fmt.Sprintf("expected error to be nil got %v", err))
} else {
fmt.Println(string(data))
}
}