Documentation
¶
Overview ¶
Package tracking provides performance tracking for database operations. This package implements query tracking, slow query detection, and structured logging for database operations across all supported database backends.
Index ¶
- Constants
- func NewConnection(conn types.Interface, log logger.Logger, cfg *config.DatabaseConfig) types.Interface
- func NewStatement(stmt types.Statement, log logger.Logger, vendor, query string, ...) types.Statement
- func NewTransaction(tx types.Tx, log logger.Logger, vendor string, settings Settings) types.Tx
- func SanitizeArgs(args []any, maxLen int) []any
- func TrackDBOperation(ctx context.Context, tc *Context, query string, args []any, start time.Time, ...)
- func TruncateString(value string, maxLen int) string
- type BasicStatement
- type Connection
- func (tc *Connection) Begin(ctx context.Context) (types.Tx, error)
- func (tc *Connection) BeginTx(ctx context.Context, opts *sql.TxOptions) (types.Tx, error)
- func (tc *Connection) Close() error
- func (tc *Connection) CreateMigrationTable(ctx context.Context) error
- func (tc *Connection) DatabaseType() string
- func (tc *Connection) Exec(ctx context.Context, query string, args ...any) (sql.Result, error)
- func (tc *Connection) GetMigrationTable() string
- func (tc *Connection) Health(ctx context.Context) error
- func (tc *Connection) Prepare(ctx context.Context, query string) (types.Statement, error)
- func (tc *Connection) Query(ctx context.Context, query string, args ...any) (*sql.Rows, error)
- func (tc *Connection) QueryRow(ctx context.Context, query string, args ...any) types.Row
- func (tc *Connection) Stats() (map[string]any, error)
- type Context
- type DB
- func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
- func (db *DB) PrepareContext(ctx context.Context, query string) (types.Statement, error)
- func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
- func (db *DB) QueryRowContext(ctx context.Context, query string, args ...any) types.Row
- type Settings
- type Statement
- type Transaction
- func (tx *Transaction) Commit() error
- func (tx *Transaction) Exec(ctx context.Context, query string, args ...any) (sql.Result, error)
- func (tx *Transaction) Prepare(ctx context.Context, query string) (types.Statement, error)
- func (tx *Transaction) Query(ctx context.Context, query string, args ...any) (*sql.Rows, error)
- func (tx *Transaction) QueryRow(ctx context.Context, query string, args ...any) types.Row
- func (tx *Transaction) Rollback() error
Constants ¶
const ( // DefaultSlowQueryThreshold defines the default threshold for slow query detection DefaultSlowQueryThreshold = 200 * time.Millisecond // DefaultMaxQueryLength defines the default maximum query length for logging DefaultMaxQueryLength = 1000 )
Variables ¶
This section is empty.
Functions ¶
func NewConnection ¶
func NewConnection(conn types.Interface, log logger.Logger, cfg *config.DatabaseConfig) types.Interface
NewConnection returns a database.Interface that wraps conn and records query/operation metrics and logs. The wrapper delegates all calls to the provided conn, uses conn.DatabaseType() NewConnection returns a types.Interface that wraps conn and records per-operation performance metrics, slow queries, and errors using the provided logger.
The wrapper uses conn.DatabaseType() as the vendor identifier and derives per-connection tracking settings from cfg via NewSettings.
func NewStatement ¶
func NewStatement(stmt types.Statement, log logger.Logger, vendor, query string, settings Settings) types.Statement
NewStatement creates a Statement wrapper that tracks performance for prepared statements. NewStatement wraps the provided statement with a tracking implementation that records execution metrics for Query, QueryRow, and Exec.
The returned types.Statement uses the supplied logger, vendor identifier, optional query string, and settings to control tracking behavior.
func NewTransaction ¶
NewTransaction creates a Transaction wrapper that tracks performance for database transactions. NewTransaction creates a Transaction wrapper around the provided tx that records execution metrics for all transaction operations. The wrapper delegates calls to the given tx while capturing timing and error information, stores the provided logger, vendor, and settings, and initializes an internal Context used for tracking.
func SanitizeArgs ¶
SanitizeArgs returns a sanitized copy of the provided argument slice suitable for logging.
If args is empty, it returns nil. String values are truncated using TruncateString with maxLen; byte slices are replaced with the placeholder "<bytes len=N>"; all other values are formatted with "%v" and then truncated using TruncateString. The returned slice has SanitizeArgs returns a sanitized copy of args suitable for logging. If args is empty it returns nil. String values are truncated to maxLen runes using TruncateString. Byte slices are replaced with the placeholder "<bytes len=N>" where N is the byte length. Other values are formatted with "%v" and then truncated to maxLen. The returned slice has the same length and element order as the input.
func TrackDBOperation ¶
func TrackDBOperation(ctx context.Context, tc *Context, query string, args []any, start time.Time, err error)
TrackDBOperation logs database operation performance metrics and errors. It provides centralized tracking for all database operations including queries, statements, and transactions. The function handles slow query detection, TrackDBOperation records metrics and emits a log event for a completed database operation.
TrackDBOperation is a no-op if tc or its Logger is nil. It records the operation's duration to request-scoped metrics, clamps the query string to the configured maximum length, and — when enabled — includes a sanitized form of parameters suitable for logging. If err is non-nil the error is logged (with sql.ErrNoRows logged at debug level); if there is no error and the duration exceeds the configured slow-query threshold a warning is emitted, otherwise a debug message is emitted.
func TruncateString ¶
TruncateString returns value truncated to at most maxLen characters. If maxLen <= 0 or value is already shorter than or equal to maxLen, the original string is returned. When maxLen <= 3 the function returns the first maxLen characters (no ellipsis); otherwise it returns the first TruncateString truncates value to at most maxLen runes, adding "..." when space allows to indicate truncation.
If maxLen <= 0 the original value is returned unchanged. If the string's rune count is less than or equal to maxLen the original value is returned. When maxLen <= 3 the function returns the first maxLen runes without an ellipsis. For maxLen > 3 the result contains the first (maxLen-3) runes followed by "...". Multi-byte characters are handled safely by operating on runes.
Types ¶
type BasicStatement ¶
BasicStatement wraps sql.Stmt to implement types.Statement interface. It provides a simple adapter between sql.Stmt and the types.Statement interface without any performance tracking (tracking is handled at higher levels).
func (*BasicStatement) Close ¶
func (s *BasicStatement) Close() error
Close closes the prepared statement
type Connection ¶
type Connection struct {
// contains filtered or unexported fields
}
Connection wraps database.Interface to provide comprehensive performance tracking. It delegates all operations to the wrapped connection while intercepting calls to log performance metrics, detect slow queries, and track errors.
func (*Connection) Close ¶
func (tc *Connection) Close() error
Close closes the database connection (no tracking needed)
func (*Connection) CreateMigrationTable ¶
func (tc *Connection) CreateMigrationTable(ctx context.Context) error
CreateMigrationTable creates the migration table if it doesn't exist with tracking
func (*Connection) DatabaseType ¶
func (tc *Connection) DatabaseType() string
DatabaseType returns the database type (no tracking needed)
func (*Connection) GetMigrationTable ¶
func (tc *Connection) GetMigrationTable() string
GetMigrationTable returns the migration table name (no tracking needed)
func (*Connection) Health ¶
func (tc *Connection) Health(ctx context.Context) error
Health checks database connection health (no tracking needed)
type Context ¶
Context groups tracking-related parameters to reduce function parameter count. This context is passed to tracking functions to provide consistent access to logger, database vendor information, and tracking settings.
type DB ¶
DB wraps sql.DB to provide request-scoped performance tracking. It intercepts all database operations and logs performance metrics, slow queries, and errors using structured logging.
func NewDB ¶
NewDB creates a DB wrapper that tracks performance for the provided *sql.DB. It records query and execution metrics (durations, truncated queries, optional parameter logging). Uses log for emitting structured logs, vendor to identify the database type, and NewDB returns a DB wrapper around the provided *sql.DB that records per-request performance metrics, slow queries, and errors using the provided logger. The wrapper is configured for the given vendor and derives per-connection tracking settings from cfg when provided.
func (*DB) ExecContext ¶
ExecContext executes a query without returning rows and tracks performance
func (*DB) PrepareContext ¶
PrepareContext prepares a statement with context and tracks performance
func (*DB) QueryContext ¶
QueryContext executes a query with context and tracks performance
type Settings ¶
type Settings struct {
// contains filtered or unexported fields
}
Settings holds configuration for database query tracking and logging. These settings control how database operations are monitored and logged.
func NewSettings ¶
func NewSettings(cfg *config.DatabaseConfig) Settings
NewSettings creates Settings populated from the provided database configuration. If cfg is nil or a numeric field is non-positive, sensible defaults are used: DefaultSlowQueryThreshold for slowQueryThreshold and DefaultMaxQueryLength for maxQueryLength. NewSettings creates a Settings configured from the provided DatabaseConfig.
It initializes defaults from DefaultSlowQueryThreshold, DefaultMaxQueryLength, and a default of false for logging query parameters. If cfg is nil the defaults are returned. When cfg is provided, cfg.Query.Slow.Threshold > 0 overrides the slow query threshold, cfg.Query.Log.MaxLength > 0 overrides the max query length, and cfg.Query.Log.Parameters is copied into the logQueryParameters flag.
func (Settings) LogQueryParameters ¶
LogQueryParameters returns whether query parameters should be logged
func (Settings) MaxQueryLength ¶
MaxQueryLength returns the maximum query length for logging
func (Settings) SlowQueryThreshold ¶
SlowQueryThreshold returns the threshold for slow query detection
type Statement ¶
type Statement struct {
// contains filtered or unexported fields
}
Statement wraps types.Statement to provide performance tracking for prepared statements. It intercepts all statement operations and logs performance metrics, slow queries, and errors using structured logging.
type Transaction ¶
type Transaction struct {
// contains filtered or unexported fields
}
Transaction wraps types.Tx to provide performance tracking for database transactions. It intercepts all transaction operations and logs performance metrics, slow queries, and errors using structured logging.
func (*Transaction) Exec ¶
Exec executes a query within a transaction without returning rows with performance tracking
func (*Transaction) Prepare ¶
Prepare prepares a statement within a transaction with performance tracking
func (*Transaction) Rollback ¶
func (tx *Transaction) Rollback() error
Rollback rolls back the transaction