sqlslog

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 15, 2025 License: MIT Imports: 6 Imported by: 0

README

sql-slog

CI codecov Go Report Card Documentation license

A logger for Go SQL database driver without modify existing *sql.DB stdlib usage.

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

INSTALL

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

USAGE

MySQL
ctx := context.TODO()
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
db, err := sqlslog.Open(ctx, "mysql", dsn, logger)
// handle err

See test for mysql for more details.

PostgreSQL
ctx := context.TODO()
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
db, err := sqlslog.Open(ctx, "postgres", dsn, logger)
// handle err

See test for postgres for more details.

SQLite3
ctx := context.TODO()
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
db, err := sqlslog.Open(ctx, "sqlite3", dsn, logger)
// handle err

See test for sqlite3 for more details.

MOTIVATION

I want to:

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

REFERENCES

CONTRIBUTE

If you found a bug, typo, wrong test, idea, help with existing issue, or anything constructive.

Don't hesitate to create an issue or pull request.

INSPIRED BY

LICENSE

MIT

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Open

func Open(ctx context.Context, driverName, dsn string, logger *slog.Logger) (*sql.DB, error)

Open opens a database specified by its database driver name and a driver-specific data source name. And returns a new database handle with logger.

Example
package main

import (
	"context"
	"log/slog"
	"os"

	sqlslog "github.com/akm/sql-slog"
)

func main() {
	dsn := "file::memory:?cache=shared"
	ctx := context.TODO()
	logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
	db, err := sqlslog.Open(ctx, "sqlite3", dsn, logger)
	if err != nil {
		// Handle error
	}
	defer db.Close()

	// Use db as a regular *sql.DB
}

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL