From 7400112fb96182b0507b7542d030d2b7b2bb99ce Mon Sep 17 00:00:00 2001 From: Hjj <582604932@qq.com> Date: Tue, 10 May 2022 14:41:01 +0800 Subject: [PATCH] test --- coupon_test.go | 8 +- db/db_coupon_comm_check.go | 6 +- utils/logx/log.go | 245 ------------------------------------- utils/logx/output.go | 104 ---------------- utils/logx/sugar.go | 192 ----------------------------- 5 files changed, 8 insertions(+), 547 deletions(-) delete mode 100644 utils/logx/log.go delete mode 100644 utils/logx/output.go delete mode 100644 utils/logx/sugar.go diff --git a/coupon_test.go b/coupon_test.go index 025c07c..e9e694f 100644 --- a/coupon_test.go +++ b/coupon_test.go @@ -7,10 +7,10 @@ import ( ) func TestCouponCommCheck(t *testing.T) { - err := Init("119.23.182.117:3306", "fnuoos_test1", "root", "Fnuo123com@") - if err != nil { - t.Errorf("Reverse == %s", err) - } + //err := Init("119.23.182.117:3306", "fnuoos_test1", "root", "Fnuo123com@") + //if err != nil { + // t.Errorf("Reverse == %s", err) + //} req := md.CouponCheckRequest{ CouponAmount: "", Uid: "21702", diff --git a/db/db_coupon_comm_check.go b/db/db_coupon_comm_check.go index d11366a..7049371 100644 --- a/db/db_coupon_comm_check.go +++ b/db/db_coupon_comm_check.go @@ -3,7 +3,7 @@ package db import ( "code.fnuoos.com/go_rely_warehouse/zyos_go_coupon.git/db/model" "code.fnuoos.com/go_rely_warehouse/zyos_go_coupon.git/utils" - "code.fnuoos.com/go_rely_warehouse/zyos_go_coupon.git/utils/logx" + "fmt" "xorm.io/xorm" ) @@ -11,6 +11,7 @@ func GetCouponUserTotalByLeaveSumWithType(Db *xorm.Engine, uid int, pvdType, col var m model.CommCouponUserTotal total, err := Db.Where("uid = "+utils.IntToStr(uid)+" and (pvd_type LIKE '%"+pvdType+"%' or pvd_type='ordinary' )").Sum(m, cols) if err != nil { + fmt.Println(err) return 0, err } return total, err @@ -20,7 +21,8 @@ func GetCouponUserTotalByLeaveSumWithType(Db *xorm.Engine, uid int, pvdType, col func CommCouponBaseList(Db *xorm.Engine) (*model.CommCoupon, error) { var CommCouponBaseList model.CommCoupon if has, err := Db.Get(&CommCouponBaseList); err != nil || !has { - return nil, logx.Error(err) + fmt.Println(err) + return nil, err } return &CommCouponBaseList, nil } diff --git a/utils/logx/log.go b/utils/logx/log.go deleted file mode 100644 index cbea10f..0000000 --- a/utils/logx/log.go +++ /dev/null @@ -1,245 +0,0 @@ -package logx - -import ( - "os" - "strings" - "time" - - "go.uber.org/zap" - "go.uber.org/zap/zapcore" -) - -type LogConfig struct { - AppName string `yaml:"app_name" json:"app_name" toml:"app_name"` - Level string `yaml:"level" json:"level" toml:"level"` - StacktraceLevel string `yaml:"stacktrace_level" json:"stacktrace_level" toml:"stacktrace_level"` - IsStdOut bool `yaml:"is_stdout" json:"is_stdout" toml:"is_stdout"` - TimeFormat string `yaml:"time_format" json:"time_format" toml:"time_format"` // second, milli, nano, standard, iso, - Encoding string `yaml:"encoding" json:"encoding" toml:"encoding"` // console, json - Skip int `yaml:"skip" json:"skip" toml:"skip"` - - IsFileOut bool `yaml:"is_file_out" json:"is_file_out" toml:"is_file_out"` - FileDir string `yaml:"file_dir" json:"file_dir" toml:"file_dir"` - FileName string `yaml:"file_name" json:"file_name" toml:"file_name"` - FileMaxSize int `yaml:"file_max_size" json:"file_max_size" toml:"file_max_size"` - FileMaxAge int `yaml:"file_max_age" json:"file_max_age" toml:"file_max_age"` -} - -var ( - l *LogX = defaultLogger() - conf *LogConfig -) - -// default logger setting -func defaultLogger() *LogX { - conf = &LogConfig{ - Level: "debug", - StacktraceLevel: "error", - IsStdOut: true, - TimeFormat: "standard", - Encoding: "console", - Skip: 2, - } - writers := []zapcore.WriteSyncer{os.Stdout} - lg, lv := newZapLogger(setLogLevel(conf.Level), setLogLevel(conf.StacktraceLevel), conf.Encoding, conf.TimeFormat, conf.Skip, zapcore.NewMultiWriteSyncer(writers...)) - zap.RedirectStdLog(lg) - return &LogX{logger: lg, atomLevel: lv} -} - -// initial standard log, if you don't init, it will use default logger setting -func InitDefaultLogger(cfg *LogConfig) { - var writers []zapcore.WriteSyncer - if cfg.IsStdOut || (!cfg.IsStdOut && !cfg.IsFileOut) { - writers = append(writers, os.Stdout) - } - if cfg.IsFileOut { - writers = append(writers, NewRollingFile(cfg.FileDir, cfg.FileName, cfg.FileMaxSize, cfg.FileMaxAge)) - } - - lg, lv := newZapLogger(setLogLevel(cfg.Level), setLogLevel(cfg.StacktraceLevel), cfg.Encoding, cfg.TimeFormat, cfg.Skip, zapcore.NewMultiWriteSyncer(writers...)) - zap.RedirectStdLog(lg) - if cfg.AppName != "" { - lg = lg.With(zap.String("app", cfg.AppName)) // 加上应用名称 - } - l = &LogX{logger: lg, atomLevel: lv} -} - -// create a new logger -func NewLogger(cfg *LogConfig) *LogX { - var writers []zapcore.WriteSyncer - if cfg.IsStdOut || (!cfg.IsStdOut && !cfg.IsFileOut) { - writers = append(writers, os.Stdout) - } - if cfg.IsFileOut { - writers = append(writers, NewRollingFile(cfg.FileDir, cfg.FileName, cfg.FileMaxSize, cfg.FileMaxAge)) - } - - lg, lv := newZapLogger(setLogLevel(cfg.Level), setLogLevel(cfg.StacktraceLevel), cfg.Encoding, cfg.TimeFormat, cfg.Skip, zapcore.NewMultiWriteSyncer(writers...)) - zap.RedirectStdLog(lg) - if cfg.AppName != "" { - lg = lg.With(zap.String("app", cfg.AppName)) // 加上应用名称 - } - return &LogX{logger: lg, atomLevel: lv} -} - -// create a new zaplog logger -func newZapLogger(level, stacktrace zapcore.Level, encoding, timeType string, skip int, output zapcore.WriteSyncer) (*zap.Logger, *zap.AtomicLevel) { - encCfg := zapcore.EncoderConfig{ - TimeKey: "T", - LevelKey: "L", - NameKey: "N", - CallerKey: "C", - MessageKey: "M", - StacktraceKey: "S", - LineEnding: zapcore.DefaultLineEnding, - EncodeCaller: zapcore.ShortCallerEncoder, - EncodeDuration: zapcore.NanosDurationEncoder, - EncodeLevel: zapcore.LowercaseLevelEncoder, - } - setTimeFormat(timeType, &encCfg) // set time type - atmLvl := zap.NewAtomicLevel() // set level - atmLvl.SetLevel(level) - encoder := zapcore.NewJSONEncoder(encCfg) // 确定encoder格式 - if encoding == "console" { - encoder = zapcore.NewConsoleEncoder(encCfg) - } - return zap.New(zapcore.NewCore(encoder, output, atmLvl), zap.AddCaller(), zap.AddStacktrace(stacktrace), zap.AddCallerSkip(skip)), &atmLvl -} - -// set log level -func setLogLevel(lvl string) zapcore.Level { - switch strings.ToLower(lvl) { - case "panic": - return zapcore.PanicLevel - case "fatal": - return zapcore.FatalLevel - case "error": - return zapcore.ErrorLevel - case "warn", "warning": - return zapcore.WarnLevel - case "info": - return zapcore.InfoLevel - default: - return zapcore.DebugLevel - } -} - -// set time format -func setTimeFormat(timeType string, z *zapcore.EncoderConfig) { - switch strings.ToLower(timeType) { - case "iso": // iso8601 standard - z.EncodeTime = zapcore.ISO8601TimeEncoder - case "sec": // only for unix second, without millisecond - z.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) { - enc.AppendInt64(t.Unix()) - } - case "second": // unix second, with millisecond - z.EncodeTime = zapcore.EpochTimeEncoder - case "milli", "millisecond": // millisecond - z.EncodeTime = zapcore.EpochMillisTimeEncoder - case "nano", "nanosecond": // nanosecond - z.EncodeTime = zapcore.EpochNanosTimeEncoder - default: // standard format - z.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) { - enc.AppendString(t.Format("2006-01-02 15:04:05.000")) - } - } -} - -func GetLevel() string { - switch l.atomLevel.Level() { - case zapcore.PanicLevel: - return "panic" - case zapcore.FatalLevel: - return "fatal" - case zapcore.ErrorLevel: - return "error" - case zapcore.WarnLevel: - return "warn" - case zapcore.InfoLevel: - return "info" - default: - return "debug" - } -} - -func SetLevel(lvl string) { - l.atomLevel.SetLevel(setLogLevel(lvl)) -} - -// temporary add call skip -func AddCallerSkip(skip int) *LogX { - l.logger.WithOptions(zap.AddCallerSkip(skip)) - return l -} - -// permanent add call skip -func AddDepth(skip int) *LogX { - l.logger = l.logger.WithOptions(zap.AddCallerSkip(skip)) - return l -} - -// permanent add options -func AddOptions(opts ...zap.Option) *LogX { - l.logger = l.logger.WithOptions(opts...) - return l -} - -func AddField(k string, v interface{}) { - l.logger.With(zap.Any(k, v)) -} - -func AddFields(fields map[string]interface{}) *LogX { - for k, v := range fields { - l.logger.With(zap.Any(k, v)) - } - return l -} - -// Normal log -func Debug(e interface{}, args ...interface{}) error { - return l.Debug(e, args...) -} -func Info(e interface{}, args ...interface{}) error { - return l.Info(e, args...) -} -func Warn(e interface{}, args ...interface{}) error { - return l.Warn(e, args...) -} -func Error(e interface{}, args ...interface{}) error { - return l.Error(e, args...) -} -func Panic(e interface{}, args ...interface{}) error { - return l.Panic(e, args...) -} -func Fatal(e interface{}, args ...interface{}) error { - return l.Fatal(e, args...) -} - -// Format logs -func Debugf(format string, args ...interface{}) error { - return l.Debugf(format, args...) -} -func Infof(format string, args ...interface{}) error { - return l.Infof(format, args...) -} -func Warnf(format string, args ...interface{}) error { - return l.Warnf(format, args...) -} -func Errorf(format string, args ...interface{}) error { - return l.Errorf(format, args...) -} -func Panicf(format string, args ...interface{}) error { - return l.Panicf(format, args...) -} -func Fatalf(format string, args ...interface{}) error { - return l.Fatalf(format, args...) -} - -func formatFieldMap(m FieldMap) []Field { - var res []Field - for k, v := range m { - res = append(res, zap.Any(k, v)) - } - return res -} diff --git a/utils/logx/output.go b/utils/logx/output.go deleted file mode 100644 index 2e6fbe7..0000000 --- a/utils/logx/output.go +++ /dev/null @@ -1,104 +0,0 @@ -package logx - -import ( - "bytes" - "gopkg.in/natefinch/lumberjack.v2" - "io" - "os" - "path/filepath" - "time" -) - -// output interface -type WriteSyncer interface { - io.Writer - Sync() error -} - -// split writer -func NewRollingFile(dir, filename string, maxSize, MaxAge int) WriteSyncer { - s, err := os.Stat(dir) - if err != nil || !s.IsDir() { - os.RemoveAll(dir) - if err := os.MkdirAll(dir, 0766); err != nil { - panic(err) - } - } - return newLumberjackWriteSyncer(&lumberjack.Logger{ - Filename: filepath.Join(dir, filename), - MaxSize: maxSize, // megabytes, MB - MaxAge: MaxAge, // days - LocalTime: true, - Compress: false, - }) -} - -type lumberjackWriteSyncer struct { - *lumberjack.Logger - buf *bytes.Buffer - logChan chan []byte - closeChan chan interface{} - maxSize int -} - -func newLumberjackWriteSyncer(l *lumberjack.Logger) *lumberjackWriteSyncer { - ws := &lumberjackWriteSyncer{ - Logger: l, - buf: bytes.NewBuffer([]byte{}), - logChan: make(chan []byte, 5000), - closeChan: make(chan interface{}), - maxSize: 1024, - } - go ws.run() - return ws -} - -func (l *lumberjackWriteSyncer) run() { - ticker := time.NewTicker(1 * time.Second) - - for { - select { - case <-ticker.C: - if l.buf.Len() > 0 { - l.sync() - } - case bs := <-l.logChan: - _, err := l.buf.Write(bs) - if err != nil { - continue - } - if l.buf.Len() > l.maxSize { - l.sync() - } - case <-l.closeChan: - l.sync() - return - } - } -} - -func (l *lumberjackWriteSyncer) Stop() { - close(l.closeChan) -} - -func (l *lumberjackWriteSyncer) Write(bs []byte) (int, error) { - b := make([]byte, len(bs)) - for i, c := range bs { - b[i] = c - } - l.logChan <- b - return 0, nil -} - -func (l *lumberjackWriteSyncer) Sync() error { - return nil -} - -func (l *lumberjackWriteSyncer) sync() error { - defer l.buf.Reset() - _, err := l.Logger.Write(l.buf.Bytes()) - if err != nil { - return err - } - return nil -} diff --git a/utils/logx/sugar.go b/utils/logx/sugar.go deleted file mode 100644 index 15ea24d..0000000 --- a/utils/logx/sugar.go +++ /dev/null @@ -1,192 +0,0 @@ -package logx - -import ( - "errors" - "fmt" - "strconv" - - "go.uber.org/zap" -) - -type LogX struct { - logger *zap.Logger - atomLevel *zap.AtomicLevel -} - -type Field = zap.Field -type FieldMap map[string]interface{} - -// 判断其他类型--start -func getFields(msg string, format bool, args ...interface{}) (string, []Field) { - var str []interface{} - var fields []zap.Field - if len(args) > 0 { - for _, v := range args { - if f, ok := v.(Field); ok { - fields = append(fields, f) - } else if f, ok := v.(FieldMap); ok { - fields = append(fields, formatFieldMap(f)...) - } else { - str = append(str, AnyToString(v)) - } - } - if format { - return fmt.Sprintf(msg, str...), fields - } - str = append([]interface{}{msg}, str...) - return fmt.Sprintln(str...), fields - } - return msg, []Field{} -} - -func (l *LogX) Debug(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.Debug(msg, field...) - } - return e -} -func (l *LogX) Info(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.Info(msg, field...) - } - return e -} -func (l *LogX) Warn(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.Warn(msg, field...) - } - return e -} -func (l *LogX) Error(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.Error(msg, field...) - } - return e -} -func (l *LogX) DPanic(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.DPanic(msg, field...) - } - return e -} -func (l *LogX) Panic(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.Panic(msg, field...) - } - return e -} -func (l *LogX) Fatal(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.Fatal(msg, field...) - } - return e -} - -func checkErr(s interface{}) (string, error) { - switch e := s.(type) { - case error: - return e.Error(), e - case string: - return e, errors.New(e) - case []byte: - return string(e), nil - default: - return "", nil - } -} - -func (l *LogX) LogError(err error) error { - return l.Error(err.Error()) -} - -func (l *LogX) Debugf(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.Debug(s, f...) - return errors.New(s) -} - -func (l *LogX) Infof(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.Info(s, f...) - return errors.New(s) -} - -func (l *LogX) Warnf(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.Warn(s, f...) - return errors.New(s) -} - -func (l *LogX) Errorf(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.Error(s, f...) - return errors.New(s) -} - -func (l *LogX) DPanicf(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.DPanic(s, f...) - return errors.New(s) -} - -func (l *LogX) Panicf(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.Panic(s, f...) - return errors.New(s) -} - -func (l *LogX) Fatalf(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.Fatal(s, f...) - return errors.New(s) -} - -func AnyToString(raw interface{}) string { - switch i := raw.(type) { - case []byte: - return string(i) - case int: - return strconv.FormatInt(int64(i), 10) - case int64: - return strconv.FormatInt(i, 10) - case float32: - return strconv.FormatFloat(float64(i), 'f', 2, 64) - case float64: - return strconv.FormatFloat(i, 'f', 2, 64) - case uint: - return strconv.FormatInt(int64(i), 10) - case uint8: - return strconv.FormatInt(int64(i), 10) - case uint16: - return strconv.FormatInt(int64(i), 10) - case uint32: - return strconv.FormatInt(int64(i), 10) - case uint64: - return strconv.FormatInt(int64(i), 10) - case int8: - return strconv.FormatInt(int64(i), 10) - case int16: - return strconv.FormatInt(int64(i), 10) - case int32: - return strconv.FormatInt(int64(i), 10) - case string: - return i - case error: - return i.Error() - } - return fmt.Sprintf("%#v", raw) -}