-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.go
More file actions
96 lines (84 loc) · 1.96 KB
/
db.go
File metadata and controls
96 lines (84 loc) · 1.96 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package log
import (
"bytes"
"context"
"path/filepath"
"time"
"github.com/gogf/gf/v2/os/glog"
"gorm.io/gorm/logger"
)
type ORMLog struct {
ctx context.Context
Level logger.LogLevel
logger *glog.Logger
}
type ORMLogOption struct {
LogOption
Level logger.LogLevel
}
func NewORMLog(opt ...*ORMLogOption) *ORMLog {
if len(opt) == 0 {
opt = append(opt, &ORMLogOption{})
}
l := glog.DefaultLogger().Clone()
if opt[0].Debug {
l.SetLevel(glog.LEVEL_ALL)
opt[0].Level = logger.Info
}
if opt[0].LogMark == "" {
opt[0].LogMark = "db"
}
l.SetFile(opt[0].LogMark + "-{Y-m-d}.log")
if opt[0].LogDir != "" {
l.SetPath(opt[0].LogDir)
}
registerLogPaths.Store(filepath.Join(l.GetPath(), opt[0].LogMark), true)
l.SetStdoutPrint(!opt[0].NoStdout)
return &ORMLog{
Level: opt[0].Level,
logger: l,
}
}
func (m *ORMLog) LogMode(l logger.LogLevel) logger.Interface {
m.Level = l
return m
}
func (m *ORMLog) Ctx() context.Context {
if m.ctx == nil {
m.ctx = context.WithValue(context.Background(), CtxMark, "ORM")
}
return m.ctx
}
func (m *ORMLog) Info(ctx context.Context, f string, a ...interface{}) {
if m.Level < logger.Info {
return
}
m.logger.Infof(m.Ctx(), f, a...)
}
func (m *ORMLog) Warn(ctx context.Context, f string, a ...interface{}) {
if m.Level < logger.Warn {
return
}
m.logger.Warningf(m.Ctx(), f, a...)
}
func (m *ORMLog) Error(ctx context.Context, f string, a ...interface{}) {
if m.Level < logger.Error {
return
}
m.logger.Errorf(m.Ctx(), f, a...)
}
func (m *ORMLog) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
// glog.Debug(m.Ctx(), "开始时间:", begin)
sql, rows := fc()
m.logger.Debug(m.Ctx(), "SQL:", sql, "行数:", rows)
if err != nil {
m.logger.Error(m.Ctx(), "错误:", err)
}
}
func (l *ORMLog) Write(p []byte) (n int, err error) {
if l.Level < logger.Info {
return len(p), nil
}
l.logger.Info(l.ctx, string(bytes.TrimRight(p, "\r\n")))
return len(p), nil
}