Skip to content

Commit 093e9c0

Browse files
committed
Init
1 parent 1accc0e commit 093e9c0

File tree

3 files changed

+87
-1
lines changed

3 files changed

+87
-1
lines changed

README.md

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,26 @@
1-
# gorm-logrus
1+
# gorm-logrus
2+
3+
```go
4+
package main
5+
6+
import (
7+
"gorm.io/gorm"
8+
"gorm.io/driver/sqlite"
9+
"github.com/onrik/gorm-logrus"
10+
)
11+
12+
type Product struct {
13+
gorm.Model
14+
Code string
15+
Price uint
16+
}
17+
18+
func main() {
19+
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{
20+
Logger: gorm_logrus.New(),
21+
})
22+
if err != nil {
23+
panic("failed to connect database")
24+
}
25+
}
26+
```

go.mod

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
module github.com/onrik/gorm-logrus
2+
3+
go 1.14
4+
5+
require (
6+
github.com/sirupsen/logrus v1.6.0
7+
gorm.io/driver/sqlite v1.1.1
8+
gorm.io/gorm v1.20.0
9+
)

logger.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package gorm_logrus
2+
3+
import (
4+
"context"
5+
"time"
6+
7+
log "github.com/sirupsen/logrus"
8+
gormlogger "gorm.io/gorm/logger"
9+
"gorm.io/gorm/utils"
10+
)
11+
12+
type logger struct {
13+
SlowThreshold time.Duration
14+
SourceField string
15+
}
16+
17+
func (l *logger) LogMode(gormlogger.LogLevel) gormlogger.Interface {
18+
return l
19+
}
20+
21+
func (l *logger) Info(ctx context.Context, s string, args ...interface{}) {
22+
log.Infof(s, args)
23+
}
24+
25+
func (l *logger) Warn(ctx context.Context, s string, args ...interface{}) {
26+
log.Warnf(s, args)
27+
}
28+
29+
func (l *logger) Error(ctx context.Context, s string, args ...interface{}) {
30+
log.Errorf(s, args)
31+
}
32+
33+
func (l *logger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
34+
elapsed := time.Since(begin)
35+
sql, _ := fc()
36+
fields := log.Fields{}
37+
if l.SourceField != "" {
38+
fields[l.SourceField] = utils.FileWithLineNum()
39+
}
40+
if err != nil {
41+
fields[log.ErrorKey] = err
42+
log.WithFields(fields).Errorf("%s [%s]", sql, elapsed)
43+
return
44+
}
45+
46+
if l.SlowThreshold != 0 && elapsed > l.SlowThreshold {
47+
log.WithFields(fields).Warnf("%s [%s]", sql, elapsed)
48+
return
49+
}
50+
51+
log.WithFields(fields).Debugf("%s [%s]", sql, elapsed)
52+
}

0 commit comments

Comments
 (0)