feat: add slog structured logging

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
tao.chen
2026-07-02 16:34:42 +08:00
co-authored by Claude Fable 5
parent 8f2f3cf271
commit ea754a85c5
16 changed files with 1432 additions and 82 deletions
+52
View File
@@ -0,0 +1,52 @@
package api
import (
"log/slog"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
// requestLogger returns a Gin middleware that logs each request via slog.
// Requests to /healthz are skipped to avoid health-check noise.
func requestLogger(lg *slog.Logger) gin.HandlerFunc {
if lg == nil {
lg = slog.Default()
}
return func(c *gin.Context) {
if c.FullPath() == "/healthz" || c.Request.URL.Path == "/healthz" {
c.Next()
return
}
start := time.Now()
c.Next()
status := c.Writer.Status()
path := c.FullPath()
if path == "" {
path = c.Request.URL.Path
}
attrs := []any{
"method", c.Request.Method,
"path", path,
"status", status,
"latency_ms", time.Since(start).Milliseconds(),
"client_ip", c.ClientIP(),
}
if len(c.Errors) > 0 {
attrs = append(attrs, "error", c.Errors.String())
}
switch {
case status >= http.StatusInternalServerError:
lg.Error("http request completed", attrs...)
case status >= http.StatusBadRequest:
lg.Warn("http request completed", attrs...)
default:
lg.Info("http request completed", attrs...)
}
}
}
+4 -2
View File
@@ -1,6 +1,7 @@
package api
import (
"log/slog"
"net/http"
"codespace/internal/service"
@@ -9,10 +10,11 @@ import (
)
// NewRouter builds a Gin engine with all API routes registered.
func NewRouter(workspaces *service.WorkspaceService, files *service.FileService, processes *service.ProcessService) *gin.Engine {
//gin.SetMode(gin.ReleaseMode)
func NewRouter(workspaces *service.WorkspaceService, files *service.FileService, processes *service.ProcessService, lg *slog.Logger) *gin.Engine {
gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.Use(gin.Recovery())
r.Use(requestLogger(lg))
wsHandler := &workspaceHandler{svc: workspaces}
fileHandler := &fileHandler{svc: files}
+3 -3
View File
@@ -17,10 +17,10 @@ func setupTestRouter(t *testing.T) http.Handler {
root := t.TempDir()
wsMgr := workspace.NewLocalManager(root)
procMgr := process.NewManager("")
wsSvc := service.NewWorkspaceService(wsMgr, procMgr)
wsSvc := service.NewWorkspaceService(wsMgr, procMgr, nil)
fileSvc := service.NewFileService(wsMgr)
procSvc := service.NewProcessService(wsMgr, procMgr)
return NewRouter(wsSvc, fileSvc, procSvc)
procSvc := service.NewProcessService(wsMgr, procMgr, nil)
return NewRouter(wsSvc, fileSvc, procSvc, nil)
}
func TestHealthz(t *testing.T) {