Files
netwatch/backend/internal/logger/logger.go
T
clawbot a4f8069047
check / check (push) Successful in 1m4s
fix(backend): cut request log fields to the log bound (closes #60)
The request log wrote the URL, User-Agent, Referer and other
request-supplied strings with no length limit, and the server accepts
headers up to 1 MiB, so one request could put about 1 MiB per field
into a log line. Every string the request log takes from the request,
including the request ID chi copies from X-Request-Id, is now cut to
the 128-byte bound the report handler already used. That bound and
its helper moved from the handlers package to the logger package so
both use the one copy.

Model: opus-5-5
2026-09-29 07:10:10 +00:00

101 lines
2.1 KiB
Go

// Package logger provides a configured slog.Logger with TTY
// detection for development vs production output.
package logger
import (
"log/slog"
"os"
"sneak.berlin/go/netwatch/internal/globals"
"go.uber.org/fx"
)
// MaxLoggedFieldBytes bounds untrusted text (request fields,
// header values, decode error text) before it is logged, so a
// caller cannot inflate log volume with an oversized value.
const MaxLoggedFieldBytes = 128
// BoundedForLog truncates an untrusted string to a fixed byte
// bound so an attacker-controlled field cannot dominate the log.
func BoundedForLog(s string) string {
if len(s) > MaxLoggedFieldBytes {
return s[:MaxLoggedFieldBytes]
}
return s
}
// Params defines the dependencies for Logger.
type Params struct {
fx.In
Globals *globals.Globals
}
// Logger wraps slog.Logger with dynamic level control.
type Logger struct {
log *slog.Logger
level *slog.LevelVar
params Params
}
// New creates a Logger with TTY-aware output formatting.
func New(_ fx.Lifecycle, params Params) (*Logger, error) {
l := new(Logger)
l.level = new(slog.LevelVar)
l.level.Set(slog.LevelInfo)
l.params = params
tty := false
if fileInfo, _ := os.Stdout.Stat(); fileInfo != nil {
if (fileInfo.Mode() & os.ModeCharDevice) != 0 {
tty = true
}
}
var handler slog.Handler
if tty {
handler = slog.NewTextHandler(
os.Stdout,
&slog.HandlerOptions{
Level: l.level,
AddSource: true,
},
)
} else {
handler = slog.NewJSONHandler(
os.Stdout,
&slog.HandlerOptions{
Level: l.level,
AddSource: true,
},
)
}
l.log = slog.New(handler)
return l, nil
}
// EnableDebugLogging sets the log level to debug.
func (l *Logger) EnableDebugLogging() {
l.level.Set(slog.LevelDebug)
l.log.Debug("debug logging enabled", "debug", true)
}
// Get returns the underlying slog.Logger.
func (l *Logger) Get() *slog.Logger {
return l.log
}
// Identify logs the application's build-time metadata.
func (l *Logger) Identify() {
l.log.Info("starting",
"appname", l.params.Globals.Appname,
"version", l.params.Globals.Version,
"buildarch", l.params.Globals.Buildarch,
)
}