fix: 慢查询/错误 SQL 日志参数化 - #6493
Conversation
WalkthroughChangesThe PR centralizes GORM configuration, adds slow-query threshold validation and driver-error sanitization, applies shared configuration across database initialization branches, updates dependency declarations, and adds logger tests. GORM logging and configuration
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant GORM
participant sanitizedLogWriter
participant sanitizeDBError
participant OutputWriter
GORM->>sanitizedLogWriter: Printf formatted trace output
sanitizedLogWriter->>sanitizeDBError: Sanitize errors when debug is disabled
sanitizeDBError-->>sanitizedLogWriter: Return reduced driver error
sanitizedLogWriter->>OutputWriter: Write configured log output
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@model/gorm_logger.go`:
- Line 26: Update the GORM logger configuration around ParameterizedQueries and
traceErrStr so enabled parameterization also prevents sensitive bound values or
tokens from appearing through separately logged driver errors. Add failing-query
coverage for every supported database, and sanitize or omit the error message
while retaining the existing SQL redaction behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 2a2fca72-5c0a-4027-948b-434fc63418c1
📒 Files selected for processing (2)
model/gorm_logger.gomodel/main.go
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@model/gorm_logger_test.go`:
- Around line 85-98: Update the test around newGormLoggerWithWriter and Trace to
assert that the returned gorm.ParamsFilter.ParamsFilter contains "secret-value"
in both DEBUG-disabled and DEBUG-enabled modes before invoking Trace, ensuring
the actual parameter-filter contract is exercised rather than relying only on
the redacted SQL placeholder.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 1791f8af-4637-4977-bcd5-8747e3a0534a
📒 Files selected for processing (3)
go.modmodel/gorm_logger.gomodel/gorm_logger_test.go
| fc := func() (string, int64) { return "SELECT * FROM t WHERE k = ?", 0 } | ||
|
|
||
| common.DebugEnabled = false | ||
| var buf bytes.Buffer | ||
| newGormLoggerWithWriter(&buf).Trace(context.Background(), time.Now(), fc, driverErr) | ||
| out := buf.String() | ||
| assert.Contains(t, out, "mysql error 1062") | ||
| assert.Contains(t, out, "k = ?") | ||
| assert.NotContains(t, out, "secret-value") | ||
|
|
||
| common.DebugEnabled = true | ||
| buf.Reset() | ||
| newGormLoggerWithWriter(&buf).Trace(context.Background(), time.Now(), fc, driverErr) | ||
| assert.Contains(t, buf.String(), "secret-value") |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Exercise the actual parameter-filter contract.
fc already returns k = ?, so this test passes even if ParameterizedQueries or ParamsFilter forwarding regresses. Assert gorm.ParamsFilter.ParamsFilter with "secret-value" in both DEBUG modes before calling Trace.
Suggested coverage
common.DebugEnabled = false
var buf bytes.Buffer
-newGormLoggerWithWriter(&buf).Trace(context.Background(), time.Now(), fc, driverErr)
+gormLogger := newGormLoggerWithWriter(&buf)
+filter, ok := gormLogger.(gorm.ParamsFilter)
+require.True(t, ok)
+sql, params := filter.ParamsFilter(context.Background(), "SELECT * FROM t WHERE k = ?", "secret-value")
+assert.Equal(t, "SELECT * FROM t WHERE k = ?", sql)
+assert.Empty(t, params)
+gormLogger.Trace(context.Background(), time.Now(), func() (string, int64) { return sql, 0 }, driverErr)As per coding guidelines, backend tests must protect real behavior and regression paths.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@model/gorm_logger_test.go` around lines 85 - 98, Update the test around
newGormLoggerWithWriter and Trace to assert that the returned
gorm.ParamsFilter.ParamsFilter contains "secret-value" in both DEBUG-disabled
and DEBUG-enabled modes before invoking Trace, ensuring the actual
parameter-filter contract is exercised rather than relying only on the redacted
SQL placeholder.
Source: Coding guidelines
* fix: parameterize slow/error SQL logs to avoid leaking credentials * fix: validate SQL_SLOW_THRESHOLD_MS range * fix: sanitize database driver error messages in SQL logs * refactor: sanitize at gorm log writer seam to keep caller attribution
* fix: parameterize slow/error SQL logs to avoid leaking credentials * fix: validate SQL_SLOW_THRESHOLD_MS range * fix: sanitize database driver error messages in SQL logs * refactor: sanitize at gorm log writer seam to keep caller attribution
* fix: parameterize slow/error SQL logs to avoid leaking credentials * fix: validate SQL_SLOW_THRESHOLD_MS range * fix: sanitize database driver error messages in SQL logs * refactor: sanitize at gorm log writer seam to keep caller attribution
* fix: parameterize slow/error SQL logs to avoid leaking credentials * fix: validate SQL_SLOW_THRESHOLD_MS range * fix: sanitize database driver error messages in SQL logs * refactor: sanitize at gorm log writer seam to keep caller attribution
* fix: parameterize slow/error SQL logs to avoid leaking credentials * fix: validate SQL_SLOW_THRESHOLD_MS range * fix: sanitize database driver error messages in SQL logs * refactor: sanitize at gorm log writer seam to keep caller attribution
📝 变更描述 / Description
gorm 未显式配置 Logger 时用默认 logger,慢查询和出错的 SQL 会把参数值内联后整句打进日志
🚀 变更类型 / Type of change
🔗 关联任务 / Related Issue
✅ 提交前检查项 / Checklist
📸 运行证明 / Proof of Work
慢查询测试:
修复前:
修复后:
错误sql测试:
修复前:
修复后:
SQL_SLOW_THRESHOLD_MS范围限制(0, 3600000)如果排查问题需要显示参数值,可临时开环境变量
DEBUG=trueSummary by CodeRabbit
New Features
0.Bug Fixes
Documentation
SQL_SLOW_THRESHOLD_MS, including valid range and default fallback behavior.Tests