-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
244 lines (214 loc) · 5.18 KB
/
main.go
File metadata and controls
244 lines (214 loc) · 5.18 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
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package main
import (
"time"
"github.com/willibrandon/mtlog"
)
// User demonstrates custom logging for sensitive data
type User struct {
ID int
Username string
Email string
Password string // Should never be logged
APIKey string // Should never be logged
LastLogin time.Time
}
// LogValue provides a safe representation for logging
func (u User) LogValue() any {
return map[string]any{
"id": u.ID,
"username": u.Username,
"email": maskEmail(u.Email),
"lastLogin": u.LastLogin,
// Password and APIKey are intentionally omitted
}
}
func maskEmail(email string) string {
if len(email) < 3 {
return "***"
}
atIndex := -1
for i, ch := range email {
if ch == '@' {
atIndex = i
break
}
}
if atIndex > 1 && atIndex < len(email)-1 {
return email[:2] + "***" + email[atIndex:]
}
return email[:1] + "***"
}
// DatabaseConnection demonstrates custom logging for connection info
type DatabaseConnection struct {
Host string
Port int
Database string
Username string
Password string // Should be masked
}
func (db DatabaseConnection) LogValue() any {
return struct {
Host string
Port int
Database string
Username string
Status string
}{
Host: db.Host,
Port: db.Port,
Database: db.Database,
Username: db.Username,
Status: "connected",
// Password is not included
}
}
// APIRequest demonstrates selective logging of HTTP requests
type APIRequest struct {
Method string
URL string
Headers map[string]string
Body []byte
}
func (r APIRequest) LogValue() any {
// Filter sensitive headers
safeHeaders := make(map[string]string)
for k, v := range r.Headers {
switch k {
case "Authorization", "X-API-Key", "Cookie":
safeHeaders[k] = "[REDACTED]"
default:
safeHeaders[k] = v
}
}
// Truncate body if too large
bodyPreview := string(r.Body)
const maxBodyLength = 200
if len(r.Body) > maxBodyLength {
bodyPreview = string(r.Body[:maxBodyLength]) + "... (truncated)"
}
return map[string]any{
"method": r.Method,
"url": r.URL,
"headers": safeHeaders,
"body": bodyPreview,
"size": len(r.Body),
}
}
// MetricSample demonstrates efficient logging of metrics
type MetricSample struct {
Name string
Value float64
Unit string
Timestamp time.Time
Tags map[string]string
}
func (m MetricSample) LogValue() any {
// Format for efficient metric logging
return struct {
Metric string
Value float64
Tags map[string]string
}{
Metric: m.Name + " (" + m.Unit + ")",
Value: m.Value,
Tags: m.Tags,
}
}
// ErrorContext represents an error with context
type ErrorContext struct {
UserID int
Operation string
Error error
Timestamp time.Time
}
// LoggableErrorContext wraps ErrorContext to implement LogValue
type LoggableErrorContext struct {
ErrorContext
}
func (e LoggableErrorContext) LogValue() any {
errorMsg := "none"
if e.Error != nil {
errorMsg = e.Error.Error()
}
return map[string]any{
"userId": e.UserID,
"operation": e.Operation,
"error": errorMsg,
"timestamp": e.Timestamp.Format(time.RFC3339),
}
}
func main() {
log := mtlog.New(
mtlog.WithConsoleProperties(),
mtlog.WithCapturing(),
)
// Example 1: User with sensitive data
user := User{
ID: 123,
Username: "alice",
Email: "alice@example.com",
Password: "super-secret-password",
APIKey: "sk_live_abcd1234",
LastLogin: time.Now(),
}
log.Information("User logged in: {@User}", user)
// Example 2: Database connection
db := DatabaseConnection{
Host: "db.example.com",
Port: 5432,
Database: "production",
Username: "dbuser",
Password: "dbpass123", // Won't be logged
}
log.Information("Connected to database: {@Database}", db)
// Example 3: API request with sensitive headers
request := APIRequest{
Method: "POST",
URL: "https://api.example.com/v1/users",
Headers: map[string]string{
"Content-Type": "application/json",
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"X-API-Key": "api_key_123456",
"X-Request-ID": "req-789",
},
Body: []byte(`{
"name": "New User",
"email": "newuser@example.com",
"preferences": {
"notifications": true,
"theme": "dark"
}
}`),
}
log.Information("API request: {@Request}", request)
// Example 4: Metrics logging
metric := MetricSample{
Name: "api.response.time",
Value: 234.5,
Unit: "ms",
Timestamp: time.Now(),
Tags: map[string]string{
"endpoint": "/v1/users",
"method": "POST",
"status": "200",
},
}
log.Information("Metric recorded: {@Metric}", metric)
// Example 5: Array of custom types
team := []User{
{ID: 1, Username: "alice", Email: "alice@example.com", Password: "pass1"},
{ID: 2, Username: "bob", Email: "bob@example.com", Password: "pass2"},
{ID: 3, Username: "charlie", Email: "charlie@example.com", Password: "pass3"},
}
log.Information("Team members: {@Team}", team)
// Example 6: Error scenarios with context
errCtx := LoggableErrorContext{
ErrorContext: ErrorContext{
UserID: user.ID,
Operation: "CreateOrder",
Error: nil, // Simulate no error
Timestamp: time.Now(),
},
}
log.Information("Operation completed: {@Context}", errCtx)
}