Logging: structured slog messages throughout, and WithLogger options so callers choose the logger

Log messages are lower-case event names with their details as key/value
attributes ("error" for errors), in place of formatted strings.

Loggable package take a WithLogger option as part of their "New*" call,
defaulting to slog.Default(). Each tags its lines with its `component`.

Some debug loggers print directly rather than using slog when in
terminal logging mode.
This commit is contained in:
bwilliams committed 2026-10-15 16:10:52 +01:00
1 parent 0b5fde9563
commit 043e307663
49 files changed
+598 -248

No files matched your search

+29 -7
View File
@@ -27,13 +27,35 @@ type Hub struct {
// max_message_size is not set.
const defaultMaxMessageSize = 32 << 10
// NewHub creates a hub.
func NewHub(conf config.JSCServerWebSocket, log *slog.Logger) *Hub {
return &Hub{
// Option configures a Hub.
type Option func(*Hub)
// WithLogger makes the hub log to logger instead of slog.Default().
func WithLogger(logger *slog.Logger) Option {
return func(h *Hub) {
h.log = logger
}
}
// NewHub creates a hub. It logs to slog.Default() unless given WithLogger.
func NewHub(conf config.JSCServerWebSocket, opts ...Option) *Hub {
hub := &Hub{
conf: conf,
log: log.With("component", "ws"),
clients: make(map[*client]struct{}),
}
for _, opt := range opts {
opt(hub)
}
return hub
}
// logger returns the logger the hub logs to, tagged with its component.
func (h *Hub) logger() *slog.Logger {
log := h.log
if log == nil {
log = slog.Default()
}
return log.With("component", "ws")
}
// Push sends a message of type msgType to every client. The payload is
@@ -45,7 +67,7 @@ func (h *Hub) Push(msgType string, payload any) {
if payload != nil {
var err error
if rawPayload, err = json.Marshal(payload); err != nil {
h.log.Error("marshal push payload", "type", msgType, "error", err)
h.logger().Error("marshal push payload", "type", msgType, "error", err)
return
}
}
@@ -55,7 +77,7 @@ func (h *Hub) Push(msgType string, payload any) {
Payload: rawPayload,
})
if err != nil {
h.log.Error("marshal push", "type", msgType, "error", err)
h.logger().Error("marshal push", "type", msgType, "error", err)
return
}
@@ -69,7 +91,7 @@ func (h *Hub) Push(msgType string, payload any) {
h.m.RUnlock()
for _, client := range slow {
h.log.Warn("dropping slow client", "client", client.id, "ip", client.ip)
h.logger().Warn("dropping slow client", "client", client.id, "ip", client.ip)
go client.close(ws.StatusPolicyViolation, "slow consumer")
}
}