Skip to content

oiime/logrusbun

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

logrusbun

A simple hook for bun that enables logging with logrus

go get github.com/oiime/logrusbun

Usage

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}),
))

QueryHookOptions

  • 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

Message template variables

  • {{.Timestamp}} Event timestmap
  • {{.Duration}} Duration of query
  • {{.Query}} Query string
  • {{.Operation}} Operation name (eg: SELECT, UPDATE...)
  • {{.Error}} Error message if available

Kitchen sink example

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}}",
})))

About

Query hook for bun orm that logs via logrus

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages