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"
  2. db := bun.NewDB(sqldb, dialect)
  3. 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),
  4. // BUNDEBUG=1 logs failed queries
  5. // BUNDEBUG=2 logs all queries
  6. bundebug.FromEnv("BUNDEBUG"),
  7. )

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)
  2. log := logrus.New()
  3. db.AddQueryHook(logrusbun.NewQueryHook(logrusbun.QueryHookOptions{Logger: log}))