Logging queries

bundebug

For quick debugging, you can print executed queries to stdout. First, you need to install bundebug package:

1. go get github.com/uptrace/bun/extra/bundebug

Then add the provided query hook which by default only prints failed queries:

1. import "github.com/uptrace/bun/extra/bundebug"

3. db := bun.NewDB(sqldb, dialect)
4. db.AddQueryHook(bundebug.NewQueryHook())

To print all queries, use WithVerbose option:

1. bundebug.NewQueryHook(bundebug.WithVerbose(true))

You can also disable the hook by default and use environment variables to enable it when needed:

1. bundebug.NewQueryHook(
2. // disable the hook
3. bundebug.WithEnabled(false),

5. // BUNDEBUG=1 logs failed queries
6. // BUNDEBUG=2 logs all queries
7. bundebug.FromEnv("BUNDEBUG"),
8. )

Logrus hook

You can also use logrusbunDebugging - 图1open in new window to log executed queries using LogrusDebugging - 图2open in new window

1. go get github.com/oiime/logrusbun

Use QueryHookOptions to adjust log levels and behavior:

1. db := bun.NewDB(sqldb, dialect)

3. log := logrus.New()
4. db.AddQueryHook(logrusbun.NewQueryHook(logrusbun.QueryHookOptions{Logger: log}))