db.go
2.2 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
package database
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/zeromicro/go-zero/core/logx"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func OpenGormDB(source string) *gorm.DB {
newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // Slow SQL threshold
LogLevel: logger.Info, // Log level
IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
Colorful: false, // Disable color
},
)
fmt.Println("starting db...")
db, err := gorm.Open(mysql.Open(source), &gorm.Config{
Logger: newLogger,
})
if err != nil {
panic(err)
}
return db
}
func OpenGormPGDB(source string, logMode string) *gorm.DB {
logx.Infof("starting db...")
db, err := gorm.Open(postgres.New(postgres.Config{
DSN: source,
PreferSimpleProtocol: true, // disables implicit prepared statement usage
}), &gorm.Config{
Logger: NewLogger(logMode), //newLogger,
})
if err != nil {
panic(err)
}
return db
}
func NewLogger(logType string) logger.Interface {
if logType == "console" {
return logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // Slow SQL threshold
LogLevel: logger.Info, // Log level
IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
Colorful: false, // Disable color
},
)
}
return ZeroLog{}
}
type ZeroLog struct {
}
func (l ZeroLog) LogMode(logger.LogLevel) logger.Interface {
return l
}
func (l ZeroLog) Info(ctx context.Context, s string, values ...interface{}) {
logx.Infof(s, values...)
}
func (l ZeroLog) Warn(ctx context.Context, s string, values ...interface{}) {
logx.Errorf(s, values...)
}
func (l ZeroLog) Error(ctx context.Context, s string, values ...interface{}) {
logx.Errorf(s, values...)
}
func (l ZeroLog) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
now := time.Now()
sql, rows := fc()
logx.Infof("[%v] [rows:%v] %s", now.Sub(begin).String(), rows, sql)
}