Categorygithub.com/akm/sql-slog
repositorypackage
0.2.0
Repository: https://github.com/akm/sql-slog.git
Documentation: pkg.go.dev

# README

sql-slog

CI codecov Enabled Linters Go Report Card Documentation license

A logger for Go SQL database drivers without modifying existing *sql.DB stdlib usage.

LOG EXAMPLES

FEATURES

  • Keep using (or re-use existing) *sql.DB as is.
  • No logger adapters. Just use log/slog
  • No dependencies except stdlib.
  • Leveled, detailed and configurable logging.
  • Duration
  • Trackable log output
    • conn_id
    • tx_id
    • stmt_id

INSTALL

go get -u github.com/akm/sql-slog

USAGE

This is a simple example of how to use sql.Open:

db, err := sql.Open("mysql", dsn)

When using sqlslog, you can use it like this:

ctx := context.TODO() // or a context.Context
db, err := sqlslog.Open(ctx, "mysql", dsn)
  1. Replace sql.Open with sqlslog.Open.
  2. Insert a context.Context as the first argument.

Features

Additional Log Levels

sqlslog provides additional log levels LevelTrace and LevelVerbose as sqlslog.Level.

To display the log levels correctly, the logger handler must be customized. You can create a handler using sqlslog.NewJSONHandler and sqlslog.NewTextHandler.

Pass an sqlslog.Option created by sqlslog.Logger to sqlslog.Open to use them.

db, err := sqlslog.Open(ctx, "sqlite3", dsn, sqlslog.Logger(yourLogger))

Configurable Log Messages and Log Levels for Each Step

In sqlslog terms, a step is a logical operation in the database driver, such as a query, a ping, a prepare, etc.

A step has three events: start, error, and complete.

sqlslog provides a way to customize the log message and log level for each step event.

You can customize them using functions that take StepOptions and return Option, like ConnPrepareContext or StmtQueryContext.

Tests

MOTIVATION

I want to:

  • Keep using *sql.DB.
    • To work with thin ORM
  • Use log/slog
    • Leverage structured logging
    • Fetch and log context.Context values if needed

REFERENCES

CONTRIBUTING

If you find a bug, typo, incorrect test, have an idea, or want to help with an existing issue, please create an issue or pull request.

INSPIRED BY

LICENSE

MIT