一个用于 Go SQL 数据库驱动程序的日志记录器,无需修改现有 *sql.DB 模块的使用。
A logger for Go SQL database driver without modify existing *sql.DB stdlib usage.
Colored console writer output above only for sample/development
*sql.DB as is.go get -u -v github.com/simukti/sqldb-loggerVersion pinning using dependency manager such as Mod or Dep is highly recommended.
As a start, Logger is just a simple interface:
type Logger interface {
Log(ctx context.Context, level Level, msg string, data map[string]interface{})
}There are 4 included basic implementation that uses well-known JSON structured logger for quickstart:
Note: those adapters does not use given context, you need to modify it and adjust with your needs.
(example: add http request id/whatever value from context to query log when you call QueryerContext andExecerContext methods)
Then for that logger to works, you need to integrate with a compatible driver which will be used by *sql.DB.
Re-use from existing *sql.DB driver, this is the simplest way:
For example, from:
dsn := "username:passwd@tcp(mysqlserver:3306)/dbname?parseTime=true"
db, err := sql.Open("mysql", dsn) // db is *sql.DB
db.Ping() // to check connectivity and DSN correctnessTo:
// import sqldblogger "github.com/simukti/sqldb-logger"
// import "github.com/simukti/sqldb-logger/logadapter/zerologadapter"
dsn := "username:passwd@tcp(mysqlserver:3306)/dbname?parseTime=true"
db, err := sql.Open("mysql", dsn) // db is *sql.DB
// handle err
loggerAdapter := zerologadapter.New(zerolog.New(os.Stdout))
db = sqldblogger.OpenDriver(dsn, db.Driver(), loggerAdapter/*, using_default_options*/) // db is STILL *sql.DB
db.Ping() // to check connectivity and DSN correctnessThat's it, all *sql.DB interaction now logged.
It is also possible to integrate with following public empty struct driver directly:
db := sqldblogger.OpenDriver(dsn, &mysql.MySQLDriver{}, loggerAdapter /*, ...options */)db := sqldblogger.OpenDriver(dsn, &pq.Driver{}, loggerAdapter /*, ...options */) db := sqldblogger.OpenDriver(dsn, &sqlite3.SQLiteDriver{}, loggerAdapter /*, ...options */)Following struct drivers maybe compatible:
db := sqldblogger.OpenDriver(dsn, &mssql.Driver{}, loggerAdapter /*, ...options */)db := sqldblogger.OpenDriver(dsn, oci8.OCI8Driver, loggerAdapter /*, ...options */)When using sqldblogger.OpenDriver(dsn, driver, logger, opt...) without 4th variadic argument, it will use default options.
Here is sample of OpenDriver() using all available options and use non-default value:
…Click here for options documentation.
I want to:
*sql.DB.context.Context value if needed. I haven't found Go *sql.DB logger with that features, so why not created myself?
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.
暂无开放 Issues,或尚未同步最近议题。