新增pgsql慢sql日志
This commit is contained in:
parent
cb23254152
commit
8b9983d218
|
@ -123,6 +123,7 @@ pgsql:
|
|||
max-open-conns: 100
|
||||
log-mode: ""
|
||||
log-zap: false
|
||||
slow-threshold: 100 # 慢查询阈值 /ms, 0为关闭
|
||||
oracle:
|
||||
path: ""
|
||||
port: ""
|
||||
|
|
|
@ -2,6 +2,7 @@ package config
|
|||
|
||||
type Pgsql struct {
|
||||
GeneralDB `yaml:",inline" mapstructure:",squash"`
|
||||
SlowThreshold int `mapstructure:"slow-threshold" json:"slow-threshold" yaml:"slow-threshold"` // 慢查询阈值,单位毫秒
|
||||
}
|
||||
|
||||
// Dsn 基于配置文件获取 dsn
|
||||
|
|
|
@ -1,11 +1,19 @@
|
|||
package initialize
|
||||
|
||||
import (
|
||||
"io"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/config"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/global"
|
||||
"github.com/flipped-aurora/gin-vue-admin/server/initialize/internal"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// GormPgSql 初始化 Postgresql 数据库
|
||||
|
@ -20,7 +28,25 @@ func GormPgSql() *gorm.DB {
|
|||
DSN: p.Dsn(), // DSN data source name
|
||||
PreferSimpleProtocol: false,
|
||||
}
|
||||
if db, err := gorm.Open(postgres.New(pgsqlConfig), internal.Gorm.Config(p.Prefix, p.Singular)); err != nil {
|
||||
|
||||
gormConfig := internal.Gorm.Config(p.Prefix, p.Singular)
|
||||
if global.GVA_CONFIG.Pgsql.SlowThreshold > 0 {
|
||||
// 定义慢查询阈值
|
||||
slowThreshold := time.Duration(global.GVA_CONFIG.Pgsql.SlowThreshold) * time.Millisecond
|
||||
|
||||
// 配置自定义日志器
|
||||
writer := io.MultiWriter(&SqlLogWriter{}, os.Stdout)
|
||||
newLogger := logger.New(
|
||||
log.New(writer, "", log.LstdFlags), // 标准日志输出
|
||||
logger.Config{
|
||||
SlowThreshold: slowThreshold, // 慢 SQL 阈值
|
||||
LogLevel: logger.Warn, // 日志级别:Warn 或 Info
|
||||
Colorful: false, // 是否启用彩色输出
|
||||
},
|
||||
)
|
||||
gormConfig.Logger = newLogger
|
||||
}
|
||||
if db, err := gorm.Open(postgres.New(pgsqlConfig), gormConfig); err != nil {
|
||||
return nil
|
||||
} else {
|
||||
sqlDB, _ := db.DB()
|
||||
|
@ -48,3 +74,14 @@ func GormPgSqlByConfig(p config.Pgsql) *gorm.DB {
|
|||
return db
|
||||
}
|
||||
}
|
||||
|
||||
type SqlLogWriter struct{}
|
||||
|
||||
func (w *SqlLogWriter) Write(p []byte) (n int, err error) {
|
||||
if strings.Contains(string(p), "SLOW SQL") {
|
||||
global.GVA_LOG.Error("SLOW-SQL", zap.String("sql", string(p)))
|
||||
} else {
|
||||
global.GVA_LOG.Info("NORMAL-SQL", zap.String("sql", string(p)))
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue