增加日志初始化

This commit is contained in:
白茶清欢 2022-06-12 18:26:19 +08:00
parent 3c9b925d73
commit 43bb73a0f6
2 changed files with 41 additions and 112 deletions

125
client.go
View File

@ -13,6 +13,7 @@ import (
"path/filepath"
"strings"
"sync"
"time"
"git.zhangdeman.cn/zhangdeman/util"
@ -43,6 +44,7 @@ func init() {
type client struct {
lock *sync.RWMutex
clientTable map[string]*DBClient
logger *zap.Logger
}
// AddWithConfigFile 使用文件生成新的客户端文件名去掉后缀作为flag
@ -209,22 +211,33 @@ func (c *client) GetSlaveClient(ctx *gin.Context, dbFlag string) (*gorm.DB, erro
// Author : go_developer@163.com<白茶清欢>
//
// Date : 20:23 2022/6/5
func (c *client) getLogInstance(logConf *LogConfig, loggerInstance *zap.Logger) (*zap.Logger, error) {
if nil != loggerInstance {
return loggerInstance, nil
}
func (c *client) getLogInstance(logConf *LogConfig) (*zap.Logger, error) {
if nil == logConf {
return nil, nil
}
logConfList := []logger.SetLoggerOptionFunc{logger.WithEncoder(logConf.Encoder), logger.WithCallerSkip(logConf.Skip), logger.WithCaller()}
if logConf.ConsoleOutput {
logConfList := []logger.SetLoggerOptionFunc{
logger.WithCallerSkip(logConf.CallerSkip),
logger.WithCaller(),
logger.WithUseJsonFormat(logConf.UseJson),
logger.WithShortCaller(logConf.UseShortFile),
}
if logConf.Console {
logConfList = append(logConfList, logger.WithConsoleOutput())
}
var (
err error
err error
loggerInstance *zap.Logger
)
if loggerInstance, err = logger.NewLogger(logConf.Level, logConf.SplitConfig, logConfList...); nil != err {
splitConfig := &logger.RotateLogConfig{
TimeIntervalType: logConf.TimeIntervalType,
LogPath: logConf.Path,
LogFileName: logConf.Name,
DivisionChar: logConf.DivisionChar,
FullLogFormat: logConf.Format,
MaxAge: time.Duration(logConf.MaxAge) * time.Second,
}
if loggerInstance, err = logger.NewLogger(logConf.LogLevel, splitConfig, logConfList...); nil != err {
return nil, err
}
return loggerInstance, nil
@ -256,7 +269,7 @@ func (c *client) GetDatabaseClient(conf *Mysql, logConf *LogConfig) (*gorm.DB, e
}
if nil != logConf {
if loggerInstance, err = getLogInstance(logConf, nil); nil != err {
if loggerInstance, err = c.getLogInstance(logConf); nil != err {
return nil, err
}
instance.Logger = wrapper.NewGormLoggerWithInstance(nil, instance, loggerInstance, "", nil)
@ -283,31 +296,6 @@ func (c *client) buildConnectionDSN(conf *Mysql) string {
)
}
// ========================== 以下是老版本支持
// NewDBClient ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 3:09 PM 2021/12/24
func NewDBClient(masterConf *DBConfig, slaveConf *DBConfig, logConf *LogConfig, loggerInstance *zap.Logger, extraRequestFieldList []string) (*DBClient, error) {
client := &DBClient{
extraFieldList: extraRequestFieldList,
}
var err error
// 日志初始化失败
if client.loggerInstance, err = getLogInstance(logConf, loggerInstance); nil != err {
return nil, err
}
if client.master, err = GetDatabaseClient(masterConf, nil); nil != err {
return nil, err
}
if client.slave, err = GetDatabaseClient(slaveConf, nil); nil != err {
return nil, err
}
return client, nil
}
// DBClient 包装日志实例
//
// Author : go_developer@163.com<白茶清欢>
@ -361,72 +349,3 @@ func (dc *DBClient) GetSlave(ctx *gin.Context) *gorm.DB {
func (dc *DBClient) getLogger(ctx *gin.Context, dbClient *gorm.DB, node string) gormLogger.Interface {
return wrapper.NewGormLoggerWithInstance(ctx, dbClient, dc.loggerInstance, node, dc.extraFieldList)
}
// getLogInstance 获取日志实例
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 3:20 PM 2021/12/24
func getLogInstance(logConf *LogConfig, loggerInstance *zap.Logger) (*zap.Logger, error) {
if nil != loggerInstance {
return loggerInstance, nil
}
if nil == logConf {
return nil, nil
}
logConfList := []logger.SetLoggerOptionFunc{logger.WithEncoder(logConf.Encoder), logger.WithCallerSkip(logConf.Skip), logger.WithCaller()}
if logConf.ConsoleOutput {
logConfList = append(logConfList, logger.WithConsoleOutput())
}
var (
err error
)
if loggerInstance, err = logger.NewLogger(logConf.Level, logConf.SplitConfig, logConfList...); nil != err {
return nil, err
}
return loggerInstance, nil
}
// GetDatabaseClient 获取日志实例
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 10:49 下午 2021/3/1
func GetDatabaseClient(conf *DBConfig, logConf *LogConfig) (*gorm.DB, error) {
var (
instance *gorm.DB
err error
loggerInstance *zap.Logger
)
if instance, err = gorm.Open(mysql.Open(buildConnectionDSN(conf)), &gorm.Config{}); nil != err {
return nil, err
}
if nil != logConf {
if loggerInstance, err = getLogInstance(logConf, nil); nil != err {
return nil, err
}
instance.Logger = wrapper.NewGormLoggerWithInstance(nil, instance, loggerInstance, "", nil)
}
return instance, nil
}
// buildConnectionDSN 构建建立连接的DSN
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 9:34 下午 2021/3/1
func buildConnectionDSN(conf *DBConfig) string {
return fmt.Sprintf(
"%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local",
conf.Username,
conf.Password,
conf.Host,
conf.Port,
conf.Database,
conf.Charset,
)
}

View File

@ -33,13 +33,22 @@ type DBConfig struct {
//
// Date : 10:51 下午 2021/3/1
type LogConfig struct {
Level zapcore.Level
ConsoleOutput bool
Encoder zapcore.Encoder
SplitConfig *logger.RotateLogConfig
ExtractFieldList []string
TraceFieldName string
Skip int
Name string `json:"name" yaml:"name"` // 日志文件名
Path string `json:"path" yaml:"path"` // 日志文件路径
Format string `json:"format" yaml:"format"` // 文件格式
TimeIntervalType logger.TimeIntervalType `json:"time_interval_type" yaml:"time_interval_type"` // 日志切割规则
DivisionChar string `json:"division_char" yaml:"division_char"` // 文件名分隔符
LogLevel zapcore.Level `json:"log_level" yaml:"log_level"` // 日志等级
Console bool `json:"console" yaml:"console"` // 是否进行控制台日志输出
UseJson bool `json:"use_json" yaml:"use_json"` // 日志是否使用JSON格式
FileLine bool `json:"file_line" yaml:"file_line"` // 日志是否打印行号
MessageKey string `json:"message_key" yaml:"message_key"` // message 字段
LevelKey string `json:"level_key" yaml:"level_key"` // level 字段
TimeKey string `json:"time_key" yaml:"time_key"` // 时间字段
CallerKey string `json:"caller_key" yaml:"caller_key"` // 记录日志的文件的代码行数
UseShortFile bool `json:"use_short_file" yaml:"use_short_file"` // 是否使用短文件格式
CallerSkip int `json:"caller_skip" yaml:"caller_skip"` // 日志记录的文件跳过多少层
MaxAge int `json:"max_age" yaml:"max_age"` // 日志最长保存时间, 单位 : 秒
}
// cfgFile 配置文件定义
@ -69,8 +78,9 @@ const (
//
// Date : 15:19 2022/6/9
type Database struct {
Master *Mysql `json:"master" yaml:"master"`
Slave *Mysql `json:"slave" yaml:"slave"`
Logger *LogConfig `json:"logger" yaml:"logger"` // 日志配置
Master *Mysql `json:"master" yaml:"master"` // 主库配置
Slave *Mysql `json:"slave" yaml:"slave"` // 从库配置
}
// Mysql ...