1package ext
2
3import (
4 "context"
5 "fmt"
6 "log/slog"
7 "time"
8
9 "gorm.io/gorm/logger"
10 "gorm.io/gorm/utils"
11)
12
13type Log struct {
14 logger *slog.Logger
15}
16
17func getFullMsg(msg string, data ...interface{}) string {
18 return fmt.Sprintf(msg, append([]interface{}{utils.FileWithLineNum()}, data...)...)
19}
20
21func (self *Log) LogMode(_ logger.LogLevel) logger.Interface {
22 return self
23}
24
25func (self *Log) Info(ctx context.Context, msg string, data ...interface{}) {
26 fullMsg := getFullMsg(msg, data)
27 self.logger.InfoContext(ctx, fullMsg)
28}
29
30func (self *Log) Warn(ctx context.Context, msg string, data ...interface{}) {
31 fullMsg := getFullMsg(msg, data)
32 self.logger.
33 WarnContext(ctx, fullMsg)
34}
35func (self *Log) Error(ctx context.Context, msg string, data ...interface{}) {
36 fullMsg := getFullMsg(msg, data)
37 self.logger.
38 ErrorContext(ctx, fullMsg)
39}
40
41func (self *Log) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), _ error) {
42 elapsed := time.Since(begin)
43 sql, _ := fc()
44 self.logger.
45 InfoContext(ctx, sql, slog.Duration("elapsed", elapsed))
46}
47
48func Wraplog(log *slog.Logger) *Log {
49 return &Log{
50 logger: log,
51 }
52}