Skip to content

Instantly share code, notes, and snippets.

@bnadland
Created September 5, 2015 16:10
Show Gist options
  • Save bnadland/2e4287b801a47dcfcc94 to your computer and use it in GitHub Desktop.
Save bnadland/2e4287b801a47dcfcc94 to your computer and use it in GitHub Desktop.
import (
log "github.com/sirupsen/logrus"
"github.com/jinzhu/gorm"
)
type GormLogger struct {}
func (*GormLogger) Print(v ...interface{}) {
if v[0] == "sql" {
log.WithFields(log.Fields{"module": "gorm", "type": "sql"}).Print(v[3])
}
if v[0] == "log" {
log.WithFields(log.Fields{"module": "gorm", "type": "log"}).Print(v[2])
}
}
func main() {
db, _ := gorm.Open(...)
defer db.Close()
db.SetLogger(&GormLogger{})
db.LogMode(true)
...
}
@CRThaze
Copy link

CRThaze commented Jul 29, 2019

Nice!

Slight variation I made:

// GormLogger is a custom logger for Gorm, making it use logrus.
type GormLogger struct{}

// Print handles log events from Gorm for the custom logger.
func (*GormLogger) Print(v ...interface{}) {
	switch v[0] {
	case "sql":
		log.WithFields(
			log.Fields{
				"module":  "gorm",
				"type":    "sql",
				"rows":    v[5],
				"src_ref": v[1],
				"values":  v[4],
			},
		).Debug(v[3])
	case "log":
		log.WithFields(log.Fields{"module": "gorm", "type": "log"}).Print(v[2])
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment