A simple hook for bun that enables logging with logrus
go get github.com/oiime/logrusbun
db := bun.NewDB(...)
log := logrus.New()
db.AddQueryHook(logrusbun.NewQueryHook(logrusbun.WithQueryHookOptions(QueryHookOptions{Logger: log})))
Similar to bundebug, additional logging setup is available:
db := bun.NewDB(...)
log := logrus.New()
db.AddQueryHook(logrusbun.NewQueryHook(
// disable the hook
logrusbun.WithEnabled(false),
// BUNDEBUG=1 logs failed queries
// BUNDEBUG=2 logs all queries
logrusbun.FromEnv("BUNDEBUG"),
// finally set logrus settings
logrusbun.WithQueryHookOptions(QueryHookOptions{Logger: log}),
))
- LogSlow time.Duration value of queries considered 'slow'
- Logger logger following logrus.FieldLogger interface
- QueryLevel logrus.Level for logging queries, eg: QueryLevel: logrus.DebugLevel
- SlowLevel logrus.Level for logging slow queries
- ErrorLevel logrus.Level for logging errors
- MessageTemplate alternative message string template, avialable variables listed below
- ErrorTemplate alternative error string template, available variables listed below
- {{.Timestamp}} Event timestmap
- {{.Duration}} Duration of query
- {{.Query}} Query string
- {{.Operation}} Operation name (eg: SELECT, UPDATE...)
- {{.Error}} Error message if available
db.AddQueryHook(NewQueryHook(WithQueryHookOptions(QueryHookOptions{
LogSlow: time.Second,
Logger: log,
QueryLevel: logrus.DebugLevel,
ErrorLevel: logrus.ErrorLevel,
SlowLevel: logrus.WarnLevel,
MessageTemplate: "{{.Operation}}[{{.Duration}}]: {{.Query}}",
ErrorTemplate: "{{.Operation}}[{{.Duration}}]: {{.Query}}: {{.Error}}",
})))