aboutsummaryrefslogtreecommitdiff
path: root/pkg/ext/gorm_logger.go
blob: ddced211a05a1b0259bc51e121230a7db390b64d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package ext

import (
	"context"
	"fmt"
	"time"

	"golang.org/x/exp/slog"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/utils"
)

type Log struct {
	logger *slog.Logger
}

func getFullMsg(msg string, data ...interface{}) string {
	return fmt.Sprintf(msg, append([]interface{}{utils.FileWithLineNum()}, data...)...)
}

func (self *Log) LogMode(_ logger.LogLevel) logger.Interface {
	return self
}

func (self *Log) Info(ctx context.Context, msg string, data ...interface{}) {
	fullMsg := getFullMsg(msg, data)
	self.logger.InfoContext(ctx, fullMsg)
}

func (self *Log) Warn(ctx context.Context, msg string, data ...interface{}) {
	fullMsg := getFullMsg(msg, data)
	self.logger.
		WarnContext(ctx, fullMsg)
}
func (self *Log) Error(ctx context.Context, msg string, data ...interface{}) {
	fullMsg := getFullMsg(msg, data)
	self.logger.
		ErrorContext(ctx, fullMsg)
}

func (self *Log) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), _ error) {
	elapsed := time.Since(begin)
	sql, _ := fc()
	self.logger.
		InfoContext(ctx, sql, slog.Duration("elapsed", elapsed))
}

func Wraplog(log *slog.Logger) *Log {
	return &Log{
		logger: log,
	}
}