1
0

fix: fix logger style err and gin warning

This commit is contained in:
2026-07-17 12:12:14 +08:00
parent 44e1415194
commit 8941f625c8
2 changed files with 60 additions and 8 deletions

View File

@@ -1,6 +1,8 @@
package logger
import (
"context"
"io"
"log/slog"
"os"
)
@@ -30,13 +32,48 @@ func toSlogLevel(level LoggerLevel) slog.Level {
}
}
// New creates a *slog.Logger that writes to os.Stderr via slog's default
// TextHandler, with its verbosity driven by the given LoggerLevel. This
// replaces the legacy module-level singleton LOGGER; callers own the returned
// logger and thread it through to sub-modules.
// New creates a *slog.Logger that writes to os.Stderr in the bracketed format
// "[<time>] [<LEVEL>] <message> [key=value ...]". Its verbosity is driven by the
// given LoggerLevel. This replaces the legacy module-level singleton LOGGER;
// callers own the returned logger and thread it through to sub-modules.
func New(level LoggerLevel) *slog.Logger {
handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
Level: toSlogLevel(level),
})
return slog.New(handler)
return slog.New(&bracketHandler{w: os.Stderr, level: toSlogLevel(level)})
}
// bracketHandler is a custom slog.Handler emitting the bracketed format
// "[<time>] [<LEVEL>] <message>" followed by any attributes as "key=value",
// matching the legacy "[LEVEL] message" style with an added timestamp.
type bracketHandler struct {
w io.Writer
level slog.Level
}
func (h *bracketHandler) Enabled(_ context.Context, l slog.Level) bool {
return l >= h.level
}
func (h *bracketHandler) Handle(_ context.Context, r slog.Record) error {
var b []byte
b = append(b, '[')
b = r.Time.AppendFormat(b, "2006-01-02T15:04:05.000-07:00")
b = append(b, "] ["...)
b = append(b, r.Level.String()...)
b = append(b, "] "...)
b = append(b, r.Message...)
r.Attrs(func(a slog.Attr) bool {
b = append(b, ' ')
b = append(b, a.Key...)
b = append(b, '=')
b = append(b, a.Value.String()...)
return true
})
b = append(b, '\n')
_, err := h.w.Write(b)
return err
}
// WithAttrs and WithGroup are no-ops: this project does not derive sub-loggers
// via Logger.With, so they simply return the receiver.
func (h *bracketHandler) WithAttrs(_ []slog.Attr) slog.Handler { return h }
func (h *bracketHandler) WithGroup(_ string) slog.Handler { return h }

View File

@@ -77,7 +77,22 @@ func fetchClientInfo(c *gin.Context) (ua, ip string) {
// Run sets up the Gin engine with all routes bound to the handler and starts
// listening on the configured web port.
func Run(handler *Handler) error {
if handler.Cfg.Others.Debug {
gin.SetMode(gin.DebugMode)
} else {
gin.SetMode(gin.ReleaseMode)
}
r := gin.Default()
err := r.SetTrustedProxies([]string{
"127.0.0.1", // IPv4 本地回环
"::1", // IPv6 本地回环
})
if err != nil {
return err
}
registerRoutes(r, handler)
return r.Run(fmt.Sprintf(":%d", handler.Cfg.Web.Port))
}