Skip to content

Commit 4e3a17e

Browse files
committed
refactor(logging): Standardize logging format across components
- Update logging in cache, auth, proxy, metrics, and fixed path middleware - Add consistent log message structure with method, path, status, and source - Improve error logging with more descriptive and uniform messages - Enhance log readability by using concise and informative log formats
1 parent 1f27799 commit 4e3a17e

File tree

5 files changed

+36
-37
lines changed

5 files changed

+36
-37
lines changed

internal/cache/manager.go

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"net/http"
1111
"os"
1212
"path/filepath"
13+
"proxy-go/internal/utils"
1314
"sort"
1415
"strings"
1516
"sync"
@@ -198,7 +199,7 @@ func (cm *CacheManager) Put(key CacheKey, resp *http.Response, body []byte) (*Ca
198199

199200
if existingItem != nil {
200201
cm.items.Store(key, existingItem)
201-
log.Printf("[Cache] Reusing existing cache for %s", key.URL)
202+
log.Printf("[Cache] HIT %s %s (%s) from %s", resp.Request.Method, key.URL, formatBytes(existingItem.Size), utils.GetRequestSource(resp.Request))
202203
return existingItem, nil
203204
}
204205

@@ -222,7 +223,7 @@ func (cm *CacheManager) Put(key CacheKey, resp *http.Response, body []byte) (*Ca
222223
}
223224

224225
cm.items.Store(key, item)
225-
log.Printf("[Cache] Cached %s (%s)", key.URL, formatBytes(item.Size))
226+
log.Printf("[Cache] NEW %s %s (%s) from %s", resp.Request.Method, key.URL, formatBytes(item.Size), utils.GetRequestSource(resp.Request))
226227
return item, nil
227228
}
228229

@@ -278,7 +279,7 @@ func (cm *CacheManager) cleanup() {
278279
cacheItem := item.(*CacheItem)
279280
os.Remove(cacheItem.FilePath)
280281
cm.items.Delete(key)
281-
log.Printf("[Cache] Removed expired item: %s", key.URL)
282+
log.Printf("[Cache] DEL %s (expired)", key.URL)
282283
}
283284
}
284285
}
@@ -365,7 +366,7 @@ func (cm *CacheManager) ClearCache() error {
365366
}
366367
filePath := filepath.Join(cm.cacheDir, entry.Name())
367368
if err := os.Remove(filePath); err != nil {
368-
log.Printf("[Cache] Failed to remove file %s: %v", filePath, err)
369+
log.Printf("[Cache] ERR Failed to remove file: %s", entry.Name())
369370
}
370371
}
371372

@@ -394,7 +395,7 @@ func (cm *CacheManager) cleanStaleFiles() error {
394395
// 清理临时文件
395396
if strings.HasPrefix(entry.Name(), "temp-") {
396397
if err := os.Remove(filePath); err != nil {
397-
log.Printf("[Cache] Failed to remove temp file %s: %v", filePath, err)
398+
log.Printf("[Cache] ERR Failed to remove temp file: %s", entry.Name())
398399
}
399400
continue
400401
}
@@ -413,7 +414,7 @@ func (cm *CacheManager) cleanStaleFiles() error {
413414
// 如果文件不在缓存记录中,删除它
414415
if !fileFound {
415416
if err := os.Remove(filePath); err != nil {
416-
log.Printf("[Cache] Failed to remove stale file %s: %v", filePath, err)
417+
log.Printf("[Cache] ERR Failed to remove stale file: %s", entry.Name())
417418
}
418419
}
419420
}
@@ -473,7 +474,7 @@ func (cm *CacheManager) Commit(key CacheKey, tempPath string, resp *http.Respons
473474

474475
cm.items.Store(key, item)
475476
cm.bytesSaved.Add(size)
476-
log.Printf("[Cache] Cached %s (%s)", key.URL, formatBytes(size))
477+
log.Printf("[Cache] NEW %s %s (%s)", resp.Request.Method, key.URL, formatBytes(size))
477478
return nil
478479
}
479480

internal/handler/auth.go

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"encoding/json"
77
"log"
88
"net/http"
9+
"proxy-go/internal/utils"
910
"strings"
1011
"sync"
1112
"time"
@@ -74,13 +75,16 @@ func (h *ProxyHandler) CheckAuth(token string) bool {
7475
func (h *ProxyHandler) LogoutHandler(w http.ResponseWriter, r *http.Request) {
7576
auth := r.Header.Get("Authorization")
7677
if auth == "" || !strings.HasPrefix(auth, "Bearer ") {
78+
log.Printf("[Auth] ERR %s %s -> 401 (%s) no token from %s", r.Method, r.URL.Path, utils.GetClientIP(r), utils.GetRequestSource(r))
7779
http.Error(w, "Unauthorized", http.StatusUnauthorized)
7880
return
7981
}
8082

8183
token := strings.TrimPrefix(auth, "Bearer ")
8284
h.auth.tokens.Delete(token)
8385

86+
log.Printf("[Auth] %s %s -> 200 (%s) logout success from %s", r.Method, r.URL.Path, utils.GetClientIP(r), utils.GetRequestSource(r))
87+
8488
w.Header().Set("Content-Type", "application/json")
8589
json.NewEncoder(w).Encode(map[string]string{
8690
"message": "已退出登录",
@@ -92,12 +96,14 @@ func (h *ProxyHandler) AuthMiddleware(next http.HandlerFunc) http.HandlerFunc {
9296
return func(w http.ResponseWriter, r *http.Request) {
9397
auth := r.Header.Get("Authorization")
9498
if auth == "" || !strings.HasPrefix(auth, "Bearer ") {
99+
log.Printf("[Auth] ERR %s %s -> 401 (%s) no token from %s", r.Method, r.URL.Path, utils.GetClientIP(r), utils.GetRequestSource(r))
95100
http.Error(w, "Unauthorized", http.StatusUnauthorized)
96101
return
97102
}
98103

99104
token := strings.TrimPrefix(auth, "Bearer ")
100105
if !h.auth.validateToken(token) {
106+
log.Printf("[Auth] ERR %s %s -> 401 (%s) invalid token from %s", r.Method, r.URL.Path, utils.GetClientIP(r), utils.GetRequestSource(r))
101107
http.Error(w, "Invalid token", http.StatusUnauthorized)
102108
return
103109
}
@@ -109,37 +115,35 @@ func (h *ProxyHandler) AuthMiddleware(next http.HandlerFunc) http.HandlerFunc {
109115
// AuthHandler 处理认证请求
110116
func (h *ProxyHandler) AuthHandler(w http.ResponseWriter, r *http.Request) {
111117
if r.Method != http.MethodPost {
112-
log.Printf("[Auth] 方法不允许: %s", r.Method)
118+
log.Printf("[Auth] ERR %s %s -> 405 (%s) method not allowed", r.Method, r.URL.Path, utils.GetClientIP(r))
113119
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
114120
return
115121
}
116122

117123
// 解析表单数据
118124
if err := r.ParseForm(); err != nil {
119-
log.Printf("[Auth] 表单解析失败: %v", err)
125+
log.Printf("[Auth] ERR %s %s -> 400 (%s) form parse error", r.Method, r.URL.Path, utils.GetClientIP(r))
120126
http.Error(w, "Invalid request", http.StatusBadRequest)
121127
return
122128
}
123129

124130
password := r.FormValue("password")
125-
log.Printf("[Auth] 收到登录请求,密码长度: %d", len(password))
126-
127131
if password == "" {
128-
log.Printf("[Auth] 密码为空")
132+
log.Printf("[Auth] ERR %s %s -> 400 (%s) empty password", r.Method, r.URL.Path, utils.GetClientIP(r))
129133
http.Error(w, "Password is required", http.StatusBadRequest)
130134
return
131135
}
132136

133137
if password != h.config.Metrics.Password {
134-
log.Printf("[Auth] 密码错误")
138+
log.Printf("[Auth] ERR %s %s -> 401 (%s) invalid password", r.Method, r.URL.Path, utils.GetClientIP(r))
135139
http.Error(w, "Invalid password", http.StatusUnauthorized)
136140
return
137141
}
138142

139143
token := h.auth.generateToken()
140144
h.auth.addToken(token, time.Duration(h.config.Metrics.TokenExpiry)*time.Second)
141145

142-
log.Printf("[Auth] 登录成功,生成令牌")
146+
log.Printf("[Auth] %s %s -> 200 (%s) login success", r.Method, r.URL.Path, utils.GetClientIP(r))
143147

144148
w.Header().Set("Content-Type", "application/json")
145149
w.WriteHeader(http.StatusOK)

internal/handler/proxy.go

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ func NewProxyHandler(cfg *config.Config) *ProxyHandler {
117117
auth: newAuthManager(),
118118
Cache: cacheManager,
119119
errorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
120-
log.Printf("[Error] %s %s -> %v", r.Method, r.URL.Path, err)
120+
log.Printf("[Error] %s %s -> %v from %s", r.Method, r.URL.Path, err, utils.GetRequestSource(r))
121121
w.WriteHeader(http.StatusInternalServerError)
122122
w.Write([]byte("Internal Server Error"))
123123
},
@@ -137,7 +137,7 @@ func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
137137
// 添加 panic 恢复
138138
defer func() {
139139
if err := recover(); err != nil {
140-
log.Printf("[Panic] %s %s -> %v", r.Method, r.URL.Path, err)
140+
log.Printf("[Panic] %s %s -> %v from %s", r.Method, r.URL.Path, err, utils.GetRequestSource(r))
141141
h.errorHandler(w, r, fmt.Errorf("panic: %v", err))
142142
}
143143
}()
@@ -157,8 +157,7 @@ func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
157157
if r.URL.Path == "/" {
158158
w.WriteHeader(http.StatusOK)
159159
fmt.Fprint(w, "Welcome to CZL proxy.")
160-
log.Printf("[%s] %s %s -> %d (root path) [%v]",
161-
utils.GetClientIP(r), r.Method, r.URL.Path, http.StatusOK, time.Since(start))
160+
log.Printf("[Proxy] %s %s -> %d (%s) from %s", r.Method, r.URL.Path, http.StatusOK, utils.GetClientIP(r), utils.GetRequestSource(r))
162161
return
163162
}
164163

@@ -176,8 +175,7 @@ func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
176175
// 如果没有匹配的路径,返回 404
177176
if matchedPrefix == "" {
178177
http.NotFound(w, r)
179-
log.Printf("[%s] %s %s -> 404 (not found) [%v]",
180-
utils.GetClientIP(r), r.Method, r.URL.Path, time.Since(start))
178+
log.Printf("[Proxy] %s %s -> 404 (%s) from %s", r.Method, r.URL.Path, utils.GetClientIP(r), utils.GetRequestSource(r))
181179
return
182180
}
183181

@@ -188,8 +186,7 @@ func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
188186
decodedPath, err := url.QueryUnescape(targetPath)
189187
if err != nil {
190188
h.errorHandler(w, r, fmt.Errorf("error decoding path: %v", err))
191-
log.Printf("[%s] %s %s -> 500 (error decoding path: %v) [%v]",
192-
utils.GetClientIP(r), r.Method, r.URL.Path, err, time.Since(start))
189+
log.Printf("[Proxy] ERR %s %s -> 500 (%s) decode error from %s", r.Method, r.URL.Path, utils.GetClientIP(r), utils.GetRequestSource(r))
193190
return
194191
}
195192

@@ -208,15 +205,15 @@ func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
208205
parsedURL, err := url.Parse(targetURL)
209206
if err != nil {
210207
h.errorHandler(w, r, fmt.Errorf("error parsing URL: %v", err))
211-
log.Printf("[%s] %s %s -> 500 (error parsing URL: %v) [%v]",
212-
utils.GetClientIP(r), r.Method, r.URL.Path, err, time.Since(start))
208+
log.Printf("[Proxy] ERR %s %s -> 500 (%s) parse error from %s", r.Method, r.URL.Path, utils.GetClientIP(r), utils.GetRequestSource(r))
213209
return
214210
}
215211

216212
// 创建新的请求时使用带超时的上下文
217213
proxyReq, err := http.NewRequestWithContext(ctx, r.Method, targetURL, r.Body)
218214
if err != nil {
219215
h.errorHandler(w, r, fmt.Errorf("error creating request: %v", err))
216+
log.Printf("[Proxy] ERR %s %s -> 500 (%s) create request error from %s", r.Method, r.URL.Path, utils.GetClientIP(r), utils.GetRequestSource(r))
220217
return
221218
}
222219

@@ -293,12 +290,10 @@ func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
293290
if err != nil {
294291
if ctx.Err() == context.DeadlineExceeded {
295292
h.errorHandler(w, r, fmt.Errorf("request timeout after %v", proxyRespTimeout))
296-
log.Printf("[Timeout] %s %s -> timeout after %v",
297-
r.Method, r.URL.Path, proxyRespTimeout)
293+
log.Printf("[Proxy] ERR %s %s -> 408 (%s) timeout from %s", r.Method, r.URL.Path, utils.GetClientIP(r), utils.GetRequestSource(r))
298294
} else {
299295
h.errorHandler(w, r, fmt.Errorf("proxy error: %v", err))
300-
log.Printf("[%s] %s %s -> 502 (proxy error: %v) [%v]",
301-
utils.GetClientIP(r), r.Method, r.URL.Path, err, time.Since(start))
296+
log.Printf("[Proxy] ERR %s %s -> 502 (%s) proxy error from %s", r.Method, r.URL.Path, utils.GetClientIP(r), utils.GetRequestSource(r))
302297
}
303298
return
304299
}
@@ -325,14 +320,14 @@ func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
325320
} else {
326321
written, err = io.Copy(w, resp.Body)
327322
if err != nil && !isConnectionClosed(err) {
328-
log.Printf("[%s] Error writing response: %v", utils.GetClientIP(r), err)
323+
log.Printf("[Proxy] ERR %s %s -> write error (%s) from %s", r.Method, r.URL.Path, utils.GetClientIP(r), utils.GetRequestSource(r))
329324
return
330325
}
331326
}
332327
} else {
333328
written, err = io.Copy(w, resp.Body)
334329
if err != nil && !isConnectionClosed(err) {
335-
log.Printf("[%s] Error writing response: %v", utils.GetClientIP(r), err)
330+
log.Printf("[Proxy] ERR %s %s -> write error (%s) from %s", r.Method, r.URL.Path, utils.GetClientIP(r), utils.GetRequestSource(r))
336331
return
337332
}
338333
}

internal/metrics/collector.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -323,13 +323,13 @@ func (c *Collector) SaveMetrics(stats map[string]interface{}) error {
323323
// LoadRecentStats 简化为只进行数据验证
324324
func (c *Collector) LoadRecentStats() error {
325325
start := time.Now()
326-
log.Printf("Starting to validate stats...")
326+
log.Printf("[Metrics] Loading stats...")
327327

328328
if err := c.validateLoadedData(); err != nil {
329329
return fmt.Errorf("data validation failed: %v", err)
330330
}
331331

332-
log.Printf("Successfully validated stats in %v", time.Since(start))
332+
log.Printf("[Metrics] Loaded stats in %v", time.Since(start))
333333
return nil
334334
}
335335

internal/middleware/fixed_path_proxy.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,7 @@ func FixedPathProxyMiddleware(configs []config.FixedPathConfig) func(http.Handle
6868
proxyReq, err := http.NewRequest(r.Method, targetURL, r.Body)
6969
if err != nil {
7070
http.Error(w, "Error creating proxy request", http.StatusInternalServerError)
71-
log.Printf("[%s] %s %s -> 500 (error creating request: %v) [%v]",
72-
utils.GetClientIP(r), r.Method, r.URL.Path, err, time.Since(startTime))
71+
log.Printf("[Fixed] ERR %s %s -> 500 (%s) create request error from %s", r.Method, r.URL.Path, utils.GetClientIP(r), utils.GetRequestSource(r))
7372
return
7473
}
7574

@@ -91,8 +90,7 @@ func FixedPathProxyMiddleware(configs []config.FixedPathConfig) func(http.Handle
9190
resp, err := client.Do(proxyReq)
9291
if err != nil {
9392
http.Error(w, "Error forwarding request", http.StatusBadGateway)
94-
log.Printf("[%s] %s %s -> 502 (proxy error: %v) [%v]",
95-
utils.GetClientIP(r), r.Method, r.URL.Path, err, time.Since(startTime))
93+
log.Printf("[Fixed] ERR %s %s -> 502 (%s) proxy error from %s", r.Method, r.URL.Path, utils.GetClientIP(r), utils.GetRequestSource(r))
9694
return
9795
}
9896
defer resp.Body.Close()
@@ -126,8 +124,9 @@ func FixedPathProxyMiddleware(configs []config.FixedPathConfig) func(http.Handle
126124
written, err = io.Copy(w, resp.Body)
127125
}
128126

127+
// 写入响应错误处理
129128
if err != nil && !isConnectionClosed(err) {
130-
log.Printf("[%s] Error writing response: %v", utils.GetClientIP(r), err)
129+
log.Printf("[Fixed] ERR %s %s -> write error (%s) from %s", r.Method, r.URL.Path, utils.GetClientIP(r), utils.GetRequestSource(r))
131130
}
132131

133132
// 记录统计信息

0 commit comments

Comments
 (0)