Skip to content

Commit

Permalink
chore: optimize log and orm (#143)
Browse files Browse the repository at this point in the history
  • Loading branch information
qloog authored Jul 19, 2024
1 parent 50c89d1 commit c776690
Show file tree
Hide file tree
Showing 8 changed files with 24 additions and 25 deletions.
9 changes: 5 additions & 4 deletions examples/log/logger.yaml
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
Development: false
DisableCaller: false
DisableStacktrace: false
Encoding: json # json or console
Level: info # 日志级别,INFO, WARN, ERROR
Name: eagle
Writers: file # 有2个可选项:file,console 选择file会将日志记录到logger_file指定的日志文件中,选择console会将日志输出到标准输出,当然也可以两者同时选择
Encoding: json # json or console
Level: info # 日志级别,INFO, WARN, ERROR
ServiceName: demo-service
Filename: demo-file
Writers: file # 有2个可选项:file,console 选择file会将日志记录到logger_file指定的日志文件中,选择console会将日志输出到标准输出,当然也可以两者同时选择
LoggerDir: /tmp/logs
LogRollingPolicy: daily
LogRotateDate: 1
Expand Down
2 changes: 1 addition & 1 deletion examples/log/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func main() {
log.Info("test log")

// print log using custom filename
log.Init(log.WithFilename("custom"))
log.Init(log.WithFilename("custom-filename"))
log.Info("test log with filename")

// print log using custom dir and filename
Expand Down
3 changes: 2 additions & 1 deletion pkg/log/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ type Config struct {
DisableStacktrace bool
Encoding string
Level string
Name string // service name
ServiceName string // service name
Fileanme string
Writers string
LoggerDir string
LogFormatText bool
Expand Down
11 changes: 7 additions & 4 deletions pkg/log/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,11 +144,14 @@ func Errorf(format string, args ...interface{}) {

// WithFields logger
// output more field, eg:
// contextLogger := log.WithFields(log.Fields{"key1": "value1"})
// contextLogger.Info("print multi field")
//
// contextLogger := log.WithFields(log.Fields{"key1": "value1"})
// contextLogger.Info("print multi field")
//
// or more sample to use:
// log.WithFields(log.Fields{"key1": "value1"}).Info("this is a test log")
// log.WithFields(log.Fields{"key1": "value1"}).Infof("this is a test log, user_id: %d", userID)
//
// log.WithFields(log.Fields{"key1": "value1"}).Info("this is a test log")
// log.WithFields(log.Fields{"key1": "value1"}).Infof("this is a test log, user_id: %d", userID)
func WithFields(keyValues Fields) Logger {
return GetLogger().WithFields(keyValues)
}
2 changes: 1 addition & 1 deletion pkg/log/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ type Option func(*Config)
// WithFilename set log filename
func WithFilename(filename string) Option {
return func(cfg *Config) {
cfg.Name = filename
cfg.Fileanme = filename
}
}

Expand Down
10 changes: 5 additions & 5 deletions pkg/log/zap.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ func buildLogger(cfg *Config, skip int) *zap.Logger {
hostname, _ = os.Hostname()
option := zap.Fields(
zap.String("ip", utils.GetLocalIP()),
zap.String("app_id", cfg.Name),
zap.String("app_id", cfg.ServiceName),
zap.String("instance_id", hostname),
)
options = append(options, option)
Expand Down Expand Up @@ -170,23 +170,23 @@ func buildLogger(cfg *Config, skip int) *zap.Logger {
}

func getAllCore(encoder zapcore.Encoder, cfg *Config) zapcore.Core {
allWriter := getLogWriterWithTime(cfg, GetLogFile(cfg.Name, logSuffix))
allWriter := getLogWriterWithTime(cfg, GetLogFile(cfg.Fileanme, logSuffix))
allLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl <= zapcore.FatalLevel
})
return zapcore.NewCore(encoder, zapcore.AddSync(allWriter), allLevel)
}

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

func getWarnCore(encoder zapcore.Encoder, cfg *Config) (zapcore.Core, zap.Option) {
warnWrite := getLogWriterWithTime(cfg, GetLogFile(cfg.Name, warnLogSuffix))
warnWrite := getLogWriterWithTime(cfg, GetLogFile(cfg.Fileanme, warnLogSuffix))
var stacktrace zap.Option
warnLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
if !cfg.DisableCaller {
Expand All @@ -200,7 +200,7 @@ func getWarnCore(encoder zapcore.Encoder, cfg *Config) (zapcore.Core, zap.Option
}

func getErrorCore(encoder zapcore.Encoder, cfg *Config) (zapcore.Core, zap.Option) {
errorFilename := GetLogFile(cfg.Name, errorLogSuffix)
errorFilename := GetLogFile(cfg.Fileanme, errorLogSuffix)
errorWrite := getLogWriterWithTime(cfg, errorFilename)
var stacktrace zap.Option
errorLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
Expand Down
5 changes: 1 addition & 4 deletions pkg/middleware/cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,6 @@ func Cors() gin.HandlerFunc {
AllowHeaders: []string{"Origin", "Authorization", "Content-Type", "Accept"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
AllowOriginFunc: func(origin string) bool {
return origin == "https://github.com"
},
MaxAge: maxAge * time.Hour,
MaxAge: maxAge * time.Hour,
})
}
7 changes: 2 additions & 5 deletions pkg/storage/orm/orm.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,21 +197,18 @@ func LoadConf(name string) (ret *Config, err error) {
// getDSN return dsn string
func getDSN(c *Config) string {
// default mysql
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=%t&loc=%s&timeout=%s%readTimeout=%s%writeTimeout=%s",
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=true&loc=Local&timeout=%s&readTimeout=%s&writeTimeout=%s",
c.UserName,
c.Password,
c.Addr,
c.Name,
true,
//"Asia/Shanghai"),
"Local",
c.Timeout,
c.ReadTimeout,
c.WriteTimeout,
)

if c.Driver == DriverPostgres {
dsn = fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=disable&connect_timeout=%s%statement_timeout=%s",
dsn = fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=disable&connect_timeout=%s&statement_timeout=%s",
c.UserName,
c.Password,
c.Addr,
Expand Down

0 comments on commit c776690

Please sign in to comment.