Skip to content

Commit

Permalink
feat: add async log and update gorm tracing (#149)
Browse files Browse the repository at this point in the history
* feat: add async log and update grom tracing

* chore: fix typo
  • Loading branch information
qloog authored Aug 22, 2024
1 parent 64fdd4f commit 8549737
Show file tree
Hide file tree
Showing 10 changed files with 87 additions and 54 deletions.
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
## Changelog
# Changelog

## v1.10.0

- feat: support async flush log to disk
- chore: using gorm offical plguin for tracing and metrics

## v1.9.0

Expand Down
23 changes: 12 additions & 11 deletions config/docker/database.yaml
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
default:
Driver: mysql # 驱动名称,目前支持 mysql,postgres,默认: mysql
Name: eagle # 数据库名称
Addr: db:3306 # 如果是 docker,可以替换为 对应的服务名称,eg: db:3306
Driver: mysql # 驱动名称,目前支持 mysql,postgres,默认: mysql
Name: eagle # 数据库名称
Addr: db:3306 # 如果是 docker,可以替换为 对应的服务名称,eg: db:3306
UserName: root
Password: root
ShowLog: true # 是否打印所有SQL日志
MaxIdleConn: 10 # 最大闲置的连接数,0意味着使用默认的大小2, 小于0表示不使用连接池
MaxOpenConn: 60 # 最大打开的连接数, 需要小于数据库配置中的max_connections数
Timeout: 3s # 数据库连接超时时间
ReadTimeout: 3s # 数据库去读超时时间, 0代表不限制
WriteTimeout: 3s # 数据库写入超时时间, 0代表不限制
ConnMaxLifeTime: 4h # 单个连接最大存活时间,建议设置比数据库超时时长(wait_timeout)稍小一些
SlowThreshold: 500ms # 慢查询阈值,设置后只打印慢查询日志,默认为200ms
ShowLog: true # 是否打印所有SQL日志
MaxIdleConn: 10 # 最大闲置的连接数,0意味着使用默认的大小2, 小于0表示不使用连接池
MaxOpenConn: 60 # 最大打开的连接数, 需要小于数据库配置中的max_connections数
Timeout: 3s # 数据库连接超时时间
ReadTimeout: 3s # 数据库去读超时时间, 0代表不限制
WriteTimeout: 3s # 数据库写入超时时间, 0代表不限制
ConnMaxLifeTime: 4h # 单个连接最大存活时间,建议设置比数据库超时时长(wait_timeout)稍小一些
SlowThreshold: 500ms # 慢查询阈值,设置后只打印慢查询日志,默认为200ms
EnableTrace: false
1 change: 1 addition & 0 deletions config/docker/logger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ LogRollingPolicy: daily
LogRotateDate: 1
LogRotateSize: 1
LogBackupCount: 7
FlushInterval: 1s
46 changes: 24 additions & 22 deletions config/local/database.yaml
Original file line number Diff line number Diff line change
@@ -1,28 +1,30 @@
default:
Driver: mysql # 驱动名称,目前支持: mysql,postgres,默认: mysql
Name: eagle # 数据库名称
Addr: localhost:3306 # 如果是 docker,可以替换为 对应的服务名称,eg: db:3306, pg:5432
Driver: mysql # 驱动名称,目前支持: mysql,postgres,默认: mysql
Name: eagle # 数据库名称
Addr: localhost:3306 # 如果是 docker,可以替换为 对应的服务名称,eg: db:3306, pg:5432
UserName: root
Password: 123456
ShowLog: true # 是否打印所有SQL日志
MaxIdleConn: 10 # 最大闲置的连接数,0意味着使用默认的大小2, 小于0表示不使用连接池
MaxOpenConn: 60 # 最大打开的连接数, 需要小于数据库配置中的max_connections数
Timeout: 3s # 数据库连接超时时间, 如果是 PostgreSQL 不需要加入单位
ReadTimeout: 3s # 数据库去读超时时间, 0代表不限制,如果是PostgreSQL, 3000代表3s
WriteTimeout: 3s # 数据库写入超时时间, 0代表不限制,如果是PostgreSQL, 不会使用该字段的值
ConnMaxLifeTime: 4h # 单个连接最大存活时间,建议设置比数据库超时时长(wait_timeout)稍小一些
SlowThreshold: 500ms # 慢查询阈值,设置后只打印慢查询日志,默认为200ms
ShowLog: true # 是否打印所有SQL日志
MaxIdleConn: 10 # 最大闲置的连接数,0意味着使用默认的大小2, 小于0表示不使用连接池
MaxOpenConn: 60 # 最大打开的连接数, 需要小于数据库配置中的max_connections数
Timeout: 3s # 数据库连接超时时间, 如果是 PostgreSQL 不需要加入单位
ReadTimeout: 3s # 数据库去读超时时间, 0代表不限制,如果是PostgreSQL, 3000代表3s
WriteTimeout: 3s # 数据库写入超时时间, 0代表不限制,如果是PostgreSQL, 不会使用该字段的值
ConnMaxLifeTime: 4h # 单个连接最大存活时间,建议设置比数据库超时时长(wait_timeout)稍小一些
SlowThreshold: 500ms # 慢查询阈值,设置后只打印慢查询日志,默认为200ms
EnableTrace: false
user:
Driver: mysql # 驱动名称,目前支持: mysql,postgres,默认: mysql
Name: eagle # 数据库名称
Addr: localhost:3306 # 如果是 docker,可以替换为 对应的服务名称,eg: db:3306, pg:5432
Driver: mysql # 驱动名称,目前支持: mysql,postgres,默认: mysql
Name: eagle # 数据库名称
Addr: localhost:3306 # 如果是 docker,可以替换为 对应的服务名称,eg: db:3306, pg:5432
UserName: root
Password: 123456
ShowLog: true # 是否打印所有SQL日志
MaxIdleConn: 10 # 最大闲置的连接数,0意味着使用默认的大小2, 小于0表示不使用连接池
MaxOpenConn: 60 # 最大打开的连接数, 需要小于数据库配置中的max_connections数
Timeout: 3s # 数据库连接超时时间
ReadTimeout: 3s # 数据库去读超时时间, 0代表不限制
WriteTimeout: 3s # 数据库写入超时时间, 0代表不限制
ConnMaxLifeTime: 4h # 单个连接最大存活时间,建议设置比数据库超时时长(wait_timeout)稍小一些
SlowThreshold: 500ms # 慢查询阈值,设置后只打印慢查询日志,默认为200ms
ShowLog: true # 是否打印所有SQL日志
MaxIdleConn: 10 # 最大闲置的连接数,0意味着使用默认的大小2, 小于0表示不使用连接池
MaxOpenConn: 60 # 最大打开的连接数, 需要小于数据库配置中的max_connections数
Timeout: 3s # 数据库连接超时时间
ReadTimeout: 3s # 数据库去读超时时间, 0代表不限制
WriteTimeout: 3s # 数据库写入超时时间, 0代表不限制
ConnMaxLifeTime: 4h # 单个连接最大存活时间,建议设置比数据库超时时长(wait_timeout)稍小一些
SlowThreshold: 500ms # 慢查询阈值,设置后只打印慢查询日志,默认为200ms
EnableTrace: false
1 change: 1 addition & 0 deletions config/local/logger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ LogRollingPolicy: daily
LogRotateDate: 1
LogRotateSize: 1
LogBackupCount: 7
FlushInterval: 1s
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -203,4 +203,5 @@ require (
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gorm.io/plugin/opentelemetry v0.1.4 // indirect
)
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -1257,11 +1257,14 @@ gorm.io/driver/postgres v1.5.4 h1:Iyrp9Meh3GmbSuyIAGyjkN+n9K+GHX9b9MqsTL4EJCo=
gorm.io/driver/postgres v1.5.4/go.mod h1:Bgo89+h0CRcdA33Y6frlaHHVuTdOf87pmyzwW9C/BH0=
gorm.io/driver/sqlite v1.1.4 h1:PDzwYE+sI6De2+mxAneV9Xs11+ZyKV6oxD3wDGkaNvM=
gorm.io/driver/sqlite v1.1.4/go.mod h1:mJCeTFr7+crvS+TRnWc5Z3UvwxUN1BGBLMrf5LA9DYw=
gorm.io/driver/sqlite v1.5.0 h1:zKYbzRCpBrT1bNijRnxLDJWPjVfImGEn0lSnUY5gZ+c=
gorm.io/gorm v1.20.7/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
gorm.io/gorm v1.20.12/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
gorm.io/gorm v1.25.2-0.20230530020048-26663ab9bf55/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
gorm.io/gorm v1.25.10 h1:dQpO+33KalOA+aFYGlK+EfxcI5MbO7EP2yYygwh9h+s=
gorm.io/gorm v1.25.10/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
gorm.io/plugin/opentelemetry v0.1.4 h1:7p0ocWELjSSRI7NCKPW2mVe6h43YPini99sNJcbsTuc=
gorm.io/plugin/opentelemetry v0.1.4/go.mod h1:tndJHOdvPT0pyGhOb8E2209eXJCUxhC5UpKw7bGVWeI=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
Expand Down
3 changes: 3 additions & 0 deletions pkg/log/config.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package log

import "time"

// Config log config
type Config struct {
Development bool
Expand All @@ -14,4 +16,5 @@ type Config struct {
LogFormatText bool
LogRollingPolicy string
LogBackupCount uint
FlushInterval time.Duration // default is 30s, recommend is dev or test is 1s, prod is 1m
}
34 changes: 27 additions & 7 deletions pkg/log/zap.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,19 +167,29 @@ func getAllCore(encoder zapcore.Encoder, cfg *Config) zapcore.Core {
allLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl <= zapcore.FatalLevel
})
return zapcore.NewCore(encoder, zapcore.AddSync(allWriter), allLevel)

asyncWriter := &zapcore.BufferedWriteSyncer{
WS: zapcore.AddSync(allWriter),
FlushInterval: cfg.FlushInterval,
}
return zapcore.NewCore(encoder, asyncWriter, allLevel)
}

func getInfoCore(encoder zapcore.Encoder, cfg *Config) zapcore.Core {
infoWrite := getLogWriterWithTime(cfg, GetLogFile(cfg.Filename, logSuffix))
infoWriter := getLogWriterWithTime(cfg, GetLogFile(cfg.Filename, logSuffix))
infoLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl <= zapcore.InfoLevel
})
return zapcore.NewCore(encoder, zapcore.AddSync(infoWrite), infoLevel)

asyncWriter := &zapcore.BufferedWriteSyncer{
WS: zapcore.AddSync(infoWriter),
FlushInterval: cfg.FlushInterval,
}
return zapcore.NewCore(encoder, asyncWriter, infoLevel)
}

func getWarnCore(encoder zapcore.Encoder, cfg *Config) (zapcore.Core, zap.Option) {
warnWrite := getLogWriterWithTime(cfg, GetLogFile(cfg.Filename, warnLogSuffix))
warnWriter := getLogWriterWithTime(cfg, GetLogFile(cfg.Filename, warnLogSuffix))
var stacktrace zap.Option
warnLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
if !cfg.DisableCaller {
Expand All @@ -189,12 +199,17 @@ func getWarnCore(encoder zapcore.Encoder, cfg *Config) (zapcore.Core, zap.Option
}
return lvl == zapcore.WarnLevel
})
return zapcore.NewCore(encoder, zapcore.AddSync(warnWrite), warnLevel), stacktrace

asyncWriter := &zapcore.BufferedWriteSyncer{
WS: zapcore.AddSync(warnWriter),
FlushInterval: cfg.FlushInterval,
}
return zapcore.NewCore(encoder, asyncWriter, warnLevel), stacktrace
}

func getErrorCore(encoder zapcore.Encoder, cfg *Config) (zapcore.Core, zap.Option) {
errorFilename := GetLogFile(cfg.Filename, errorLogSuffix)
errorWrite := getLogWriterWithTime(cfg, errorFilename)
errorWriter := getLogWriterWithTime(cfg, errorFilename)
var stacktrace zap.Option
errorLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
if !cfg.DisableCaller {
Expand All @@ -204,7 +219,12 @@ func getErrorCore(encoder zapcore.Encoder, cfg *Config) (zapcore.Core, zap.Optio
}
return lvl >= zapcore.ErrorLevel
})
return zapcore.NewCore(encoder, zapcore.AddSync(errorWrite), errorLevel), stacktrace

asyncWriter := &zapcore.BufferedWriteSyncer{
WS: zapcore.AddSync(errorWriter),
FlushInterval: cfg.FlushInterval,
}
return zapcore.NewCore(encoder, asyncWriter, errorLevel), stacktrace
}

// getLogWriterWithTime 按时间(小时)进行切割
Expand Down
22 changes: 9 additions & 13 deletions pkg/storage/orm/orm.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,14 @@ import (
"sync"
"time"

"github.com/go-eagle/eagle/pkg/config"

otelgorm "github.com/1024casts/gorm-opentelemetry"
"gorm.io/driver/clickhouse"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"

// GORM MySQL
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/plugin/opentelemetry/tracing"

"github.com/go-eagle/eagle/pkg/config"
)

const (
Expand Down Expand Up @@ -54,6 +52,7 @@ type Config struct {
WriteTimeout string
ConnMaxLifeTime time.Duration
SlowThreshold time.Duration // 慢查询时长,默认500ms
EnableTrace bool
}

// New create a or multi database client
Expand Down Expand Up @@ -164,15 +163,12 @@ func NewInstance(c *Config) (db *gorm.DB) {

db.Set("gorm:table_options", "CHARSET=utf8mb4")

// Initialize otel plugin with options
plugin := otelgorm.NewPlugin(
// include any options here
)

// set trace
err = db.Use(plugin)
if err != nil {
log.Panicf("using gorm opentelemetry, err: %+v", err)
if c.EnableTrace {
err = db.Use(tracing.NewPlugin())
if err != nil {
log.Panicf("using gorm opentelemetry, err: %+v", err)
}
}

return db
Expand Down

0 comments on commit 8549737

Please sign in to comment.