feat(platform)!: log exclusively as structured json
Request access logs, panics, migration output and fatal errors are now emitted through the JSON slog handler. BREAKING CHANGE: UPTIME_LOG_FORMAT is removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
8d1093cd2d
commit
e9c7394c8b
8 files changed
+108
-48
No files matched your search
@@ -0,0 +1,60 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
var quietPaths = map[string]bool{"/healthz": true, "/readyz": true}
|
||||
|
||||
func NewRouter(log *slog.Logger) *gin.Engine {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
gin.DefaultWriter = io.Discard
|
||||
gin.DefaultErrorWriter = io.Discard
|
||||
r := gin.New()
|
||||
r.Use(accessLog(log), recovery(log))
|
||||
return r
|
||||
}
|
||||
|
||||
func accessLog(log *slog.Logger) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
start := time.Now()
|
||||
c.Next()
|
||||
if quietPaths[c.Request.URL.Path] && c.Writer.Status() < 500 {
|
||||
return
|
||||
}
|
||||
attrs := []any{
|
||||
"method", c.Request.Method,
|
||||
"path", c.Request.URL.Path,
|
||||
"route", c.FullPath(),
|
||||
"status", c.Writer.Status(),
|
||||
"duration_ms", time.Since(start).Milliseconds(),
|
||||
"bytes", c.Writer.Size(),
|
||||
"client_ip", c.ClientIP(),
|
||||
}
|
||||
if len(c.Errors) > 0 {
|
||||
attrs = append(attrs, "errors", c.Errors.Errors())
|
||||
}
|
||||
level := slog.LevelInfo
|
||||
switch {
|
||||
case c.Writer.Status() >= 500:
|
||||
level = slog.LevelError
|
||||
case c.Writer.Status() >= 400:
|
||||
level = slog.LevelWarn
|
||||
}
|
||||
log.Log(c.Request.Context(), level, "http request", attrs...)
|
||||
}
|
||||
}
|
||||
|
||||
func recovery(log *slog.Logger) gin.HandlerFunc {
|
||||
return gin.CustomRecoveryWithWriter(io.Discard, func(c *gin.Context, err any) {
|
||||
log.ErrorContext(c.Request.Context(), "panic",
|
||||
"error", err, "path", c.Request.URL.Path, "stack", string(debug.Stack()))
|
||||
c.AbortWithStatus(http.StatusInternalServerError)
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user