Logging & slow queries
The logger.Interface surface, level gating, gorm-parity trace lines, slow-query warnings, parameterized logging, and Debug().
Every executed statement flows through one logger call. fusion-orm's
logging is a small interface plus a stdlib default implementation and a
log/slog adapter — no third-party logger is required, and any of the
built-in implementations can be replaced wholesale.
The interface
// Interface is the logger surface used throughout fusion-orm.
//
// Trace is called once per executed statement: begin is the start time, fc
// lazily produces the SQL text and rows-affected count (pass -1 for
// unknown), and err is the statement error (nil on success).type Interface interface {
// LogMode returns a copy of the logger gated at level.
LogMode(level LogLevel) Interface
// Info logs an informational message.
Info(ctx context.Context, msg string, data ...any)
// Warn logs a warning message.
Warn(ctx context.Context, msg string, data ...any)
// Error logs an error message.
Error(ctx context.Context, msg string, data ...any)
// Trace logs a completed SQL statement.
Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error)
}Trace is the hot path. The fc closure is lazy: the logger calls it only
when it decides to emit a line, and it returns the final SQL text (with
vars interpolated) plus the affected-row count (-1 when unknown).
LogMode returns a copy — it never mutates the receiver.
Levels
const (
// Silent disables all output, including SQL traces.
Silent LogLevel = iota + 1
// Error logs failed SQL traces and Error/Warn/Info calls.
Error
// Warn additionally logs slow SQL traces and Warn/Info calls.
Warn
// Info additionally logs every SQL trace and Info calls.
Info
)Levels are cumulative: Warn shows errors and slow queries, Info shows
every statement.
Trace line format
The stdlib logger renders gorm-parity lines:
[0.123ms] [rows:1] SELECT * FROM users WHERE id = 1
SLOW SQL >= 200ms [0.300ms] [rows:1] SELECT ...
ERROR record not found [1.000ms] [rows:-1] SELECT ...Slow-query detection is threshold-based; a nanosecond threshold makes everything slow, which the tests exploit:
l := New(w, Config{LogLevel: Warn, SlowThreshold: time.Nanosecond})
begin := time.Now().Add(-time.Hour)
l.Trace(context.Background(), begin, func() (string, int64) {
return "SELECT slow", -1
}, nil)
got := w.String()
if !strings.HasPrefix(got, "SLOW SQL >= 1ns ") {
t.Fatalf("slow trace = %q", got)
}Errors print the error text first; ErrRecordNotFound is suppressed when
IgnoreRecordNotFoundError is set (the expected First/Take/Last
miss).
Config and presets
type Config struct {
// SlowThreshold marks traces slower than this as warnings. Zero
// disables slow-SQL detection.
SlowThreshold time.Duration
// LogLevel gates output; the zero value means Warn.
LogLevel LogLevel
// IgnoreRecordNotFoundError suppresses traces whose error is
// ErrRecordNotFound (common and expected on First/Take/Last misses).
IgnoreRecordNotFoundError bool
// ParameterizedQueries strips bound variables from logged SQL so
// user data never reaches the log.
ParameterizedQueries bool
// Colorful enables ANSI colors in the stdlib writer output.
Colorful bool
}Two presets ship in the package:
var (
// Discard drops everything.
Discard = New(log.New(io.Discard, "", log.LstdFlags), Config{LogLevel: Silent})
// Default writes to stdout at Warn with a 200ms slow threshold.
Default = New(log.New(os.Stdout, "", log.LstdFlags), Config{
LogLevel: Warn,
SlowThreshold: 200 * time.Millisecond,
})
)Open falls back to logger.Default when Config.Logger is nil. Build
your own against any Printf-style sink:
// New builds an Interface writing to writer under config.
func New(writer Writer, config Config) Interface {db := openTestDB(t, &Config{Logger: logger.New(w, logger.Config{LogLevel: logger.Warn})})For structured logs, swap in the slog adapter — trace events become an
attribute group with duration, sql, rows, and error keys:
// NewSlogLogger returns an Interface that writes through the given slog
// logger. Trace events are emitted as a "trace" attribute group with
// duration/sql/rows/error keys.
func NewSlogLogger(l *slog.Logger, config Config) Interface {Discard in tests, Default in scripts
logger.Discard keeps test output clean at zero cost. The default's
Warn/200ms combination is deliberately quiet: in steady state you only hear
about failures and slow statements.
Optional interfaces: ParamsFilter and Tracer
Two capabilities a logger may implement beyond Interface:
// ParamsFilter is an optional interface a logger can implement to rewrite
// the SQL/params pair before it reaches Trace. With ParameterizedQueries
// enabled the bound variables are dropped so secrets never reach the log.
type ParamsFilter interface {
ParamsFilter(ctx context.Context, sql string, params ...any) (string, []any)
}type Tracer interface {
// WouldTrace reports whether Trace would invoke fc and emit output for
// the given elapsed time and error.
WouldTrace(elapsed time.Duration, err error) bool
}The query path consults WouldTrace before building the fc closure:
// Gated loggers skip the closure allocation entirely when no line can
// result (Warn-level default with no error and a fast query). Loggers
// that do not implement logger.Tracer are always called, as before.
if t, ok := db.Logger.(logger.Tracer); ok && !t.WouldTrace(time.Since(begin), err) {
return
}Both built-in loggers implement Tracer, so a Warn-gated session with a
fast, successful query allocates nothing. When a line is emitted, the
closure runs ParamsFilter first and then interpolates the remaining vars
through the dialector for display.
ParameterizedQueries: logs placeholders, never values
if l.config.ParameterizedQueries {
return sql, nil
}
return sql, paramsWith ParameterizedQueries: true, the params are dropped before
interpolation, so logs show WHERE id = ? instead of WHERE id = 42.
Use it in production: bound variables routinely carry PII, and log
aggregators are a breach surface. The trade-off is that logged SQL is no
longer copy-paste runnable — flip it off temporarily when debugging.
Debug()
db.Debug() returns a derivative whose logger is the receiver's logger
regated to Info — every statement on that chain traces, while the root
stays quiet:
func (db *DB) Debug() *DB {
tx := db.getInstance()
return tx.Session(&Session{Logger: db.Logger.LogMode(logger.Info)})
}// Root logger is Warn: a successful trace must not be printed.
if tx := db.Exec("SELECT 1"); tx.Error != nil {
t.Fatalf("root Exec: %v", tx.Error)
}
if got := w.String(); got != "" {
t.Fatalf("root Exec at Warn logged %q", got)
}
// Debug installs an Info-gated derivative logger.
if tx := db.Debug().Exec("SELECT 2"); tx.Error != nil {
t.Fatalf("Debug Exec: %v", tx.Error)
}
got := w.String()
if !strings.Contains(got, "SELECT 2") {
t.Fatalf("Debug Exec did not trace, logged %q", got)
}Because it is a derivative, Debug() composes like any chainable —
db.Debug().Where(...).Find(...) — and expires at the end of the chain.