diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/.DS_Store differ diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index a460645..0000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "go.inferGopath": false -} \ No newline at end of file diff --git a/go.mod b/go.mod index 7567c55..765e15e 100644 --- a/go.mod +++ b/go.mod @@ -26,13 +26,15 @@ require ( github.com/nsf/termbox-go v0.0.0-20200418040025-38ba6e5628f1 // indirect github.com/nsqio/go-nsq v1.0.8 github.com/olivere/elastic v6.2.31+incompatible - github.com/pkg/errors v0.9.1 // indirect + github.com/pkg/errors v0.9.1 github.com/spf13/cobra v1.0.0 github.com/syndtr/goleveldb v1.0.0 + go.uber.org/zap v1.10.0 golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd golang.org/x/image v0.0.0-20200430140353-33d19683fad8 // indirect golang.org/x/net v0.0.0-20200506145744-7e3656a0809f golang.org/x/text v0.3.2 gopkg.in/eapache/queue.v1 v1.1.0 gopkg.in/go-with/wxpay.v1 v1.3.0 + gopkg.in/natefinch/lumberjack.v2 v2.0.0 ) diff --git a/go.sum b/go.sum index bfd570a..51ab825 100644 --- a/go.sum +++ b/go.sum @@ -177,8 +177,11 @@ github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= github.com/xxjwxc/oauth2 v0.0.0-20200316140438-ddd4e3c5f272 h1:aKA2UeM+nzEanWpzZWqkD3e12FlX6bRdhcOsNhm21X0= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= +go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/multierr v1.1.0 h1:HoEmRHQPVSqub6w2z2d2EOVs2fjyFRGyofhKuyDq0QI= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/zap v1.10.0 h1:ORx85nbTijNz8ljznvCMR1ZBIPKFn3jQrag10X2AsuM= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= @@ -246,6 +249,8 @@ gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/go-with/wxpay.v1 v1.3.0 h1:RXVQck9qNIGkajbTMCvlRPHeewyAIItzOybTTykVdV0= gopkg.in/go-with/wxpay.v1 v1.3.0/go.mod h1:12lWy92n19pAUSSE3BrOiEZbWRkl+9tneOd/aU/LU6g= +gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8= +gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= diff --git a/mycatch/mycatch.go b/mycatch/mycatch.go index 1c2c9ae..855c2f4 100644 --- a/mycatch/mycatch.go +++ b/mycatch/mycatch.go @@ -10,13 +10,12 @@ package mycatch import ( "fmt" - "os" "runtime/debug" - "time" - "github.com/xxjwxc/public/tools" + "github.com/xxjwxc/public/mylog" ) +// Dmp dmp the recover func Dmp() { errstr := "" if err := recover(); err != nil { @@ -25,28 +24,29 @@ func Dmp() { } errstr += (string(debug.Stack())) //输出堆栈信息 - OnPrintErr(errstr) + mylog.Panic(errstr, "err") + // OnPrintErr(errstr) } -func OnPrintErr(errstring string) { - path := tools.GetCurrentDirectory() + "/err" - if !tools.CheckFileIsExist(path) { - os.MkdirAll(path, os.ModePerm) //生成多级目录 - } +// func OnPrintErr(errstring string) { +// path := tools.GetCurrentDirectory() + "/err" +// if !tools.CheckFileIsExist(path) { +// os.MkdirAll(path, os.ModePerm) //生成多级目录 +// } - now := time.Now() //获取当前时间 - pid := os.Getpid() //获取进程ID - time_str := now.Format("2006-01-02") //设定时间格式 - fname := fmt.Sprintf("%s/panic_%s-%x.log", path, time_str, pid) //保存错误信息文件名:程序名-进程ID-当前时间(年月日时分秒) - fmt.Println("panic to file ", fname) +// now := time.Now() //获取当前时间 +// pid := os.Getpid() //获取进程ID +// timeStr := now.Format("2006-01-02") //设定时间格式 +// fname := fmt.Sprintf("%s/panic_%s-%x.log", path, timeStr, pid) //保存错误信息文件名:程序名-进程ID-当前时间(年月日时分秒) +// fmt.Println("panic to file ", fname) - f, err := os.OpenFile(fname, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666) - if err != nil { - return - } - defer f.Close() +// f, err := os.OpenFile(fname, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666) +// if err != nil { +// return +// } +// defer f.Close() - f.WriteString("=========================" + now.Format("2006-01-02 15:04:05 ========================= \r\n")) - f.WriteString(errstring) //输出堆栈信息 - f.WriteString("=========================end=========================") -} +// f.WriteString("=========================" + now.Format("2006-01-02 15:04:05 ========================= \r\n")) +// f.WriteString(errstring) //输出堆栈信息 +// f.WriteString("=========================end=========================") +// } diff --git a/mydraw/mydraw.go b/mydraw/mydraw.go index 5a10a7b..967b775 100644 --- a/mydraw/mydraw.go +++ b/mydraw/mydraw.go @@ -95,7 +95,7 @@ func (this *HDC) DrawText(pen Pen, text string) bool { for _, s := range strings.Split(text, "\r\n") { _, err := c.DrawString(s, pt) if err != nil { - mylog.Println("c.DrawString(%s) error(%v)", s, err) + mylog.Infof("c.DrawString(%s) error(%v)", s, err) return false } pt.Y += c.PointToFixed(pen.FontSize * 1.5) @@ -118,9 +118,7 @@ func (this *HDC) Save(imagePath string) bool { err = jpeg.Encode(output, this.Rgba, nil) } if err != nil { - - mylog.Println("image encode error(%v)", err) - //mylog.Error(err) + mylog.Infof("image encode error(%v)", err) return false } return true diff --git a/myelastic/myelastic.go b/myelastic/myelastic.go index 1c0d97a..d06baba 100644 --- a/myelastic/myelastic.go +++ b/myelastic/myelastic.go @@ -37,7 +37,7 @@ func OnInitES(url string) MyElastic { //func (es *MyElastic) Model(refs interface{}) *MyElastic { // if reflect.ValueOf(refs).Type().Kind() != reflect.Ptr { -// mylog.Println("Model: attempt to Model into a pointer") +// mylog.Info("Model: attempt to Model into a pointer") // panic(0) // } diff --git a/mylog/common.go b/mylog/common.go new file mode 100644 index 0000000..dc08102 --- /dev/null +++ b/mylog/common.go @@ -0,0 +1,75 @@ +package mylog + +import ( + "fmt" + "os" + "path/filepath" + "runtime/debug" + "strings" + "sync" + "time" +) + +type errDeal struct { + once sync.Once + _path string +} + +func (s *errDeal) initPath() { + s._path = getCurrentDirectory() + "/err" + os.MkdirAll(s._path, os.ModePerm) //生成多级目录 +} + +// SaveError 保存错误信息 +func (s *errDeal) SaveError(errstring, flag string) { + s.once.Do(s.initPath) + + now := time.Now() //获取当前时间 + timeStr := now.Format("2006-01-02_15") //设定时间格式 + fname := fmt.Sprintf("%s/%s_%s.log", s._path, flag, timeStr) //保存错误信息文件名:程序名-进程ID-当前时间(年月日时分秒) + + f, err := os.OpenFile(fname, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666) + if err != nil { + return + } + defer f.Close() + + f.WriteString("=========================" + now.Format("2006-01-02 15:04:05 ========================= \r\n")) + f.WriteString(errstring + "\r\n") //输出堆栈信息 + f.WriteString(string(debug.Stack()) + "\r\n") //输出堆栈信息) + f.WriteString("=========================end=========================\r\n") +} + +// Panic return trace of error +func (s *errDeal) Panic(a ...interface{}) { + s.once.Do(s.initPath) + + now := time.Now() //获取当前时间 + pid := os.Getpid() //获取进程ID + timeStr := now.Format("2006-01-02") //设定时间格式 + fname := fmt.Sprintf("%s/panic_%s-%x.log", s._path, timeStr, pid) //保存错误信息文件名:程序名-进程ID-当前时间(年月日时分秒) + fmt.Println("panic to file ", fname) + + f, err := os.OpenFile(fname, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666) + if err != nil { + return + } + defer f.Close() + + f.WriteString("=========================" + now.Format("2006-01-02 15:04:05 ========================= \r\n")) + f.WriteString(getStr(a...)) //输出堆栈信息 + f.WriteString("=========================end=========================") +} + +// GetCurrentDirectory 获取exe所在目录 +func getCurrentDirectory() string { + dir, _ := os.Executable() + exPath := filepath.Dir(dir) + // fmt.Println(exPath) + + return exPath +} + +func getStr(a ...interface{}) string { + return fmt.Sprintf(strings.Repeat("[%+v]", len(a)), a...) +} diff --git a/mylog/def.go b/mylog/def.go deleted file mode 100644 index 08f5daa..0000000 --- a/mylog/def.go +++ /dev/null @@ -1,83 +0,0 @@ -package mylog - -import ( - "time" -) - -/* - 日志详细信息 -*/ -type LogInfo struct { - Service string `json:"service"` //服务名 - Group string `json:"group"` //服务组 - Type string `json:"type"` //日志的类型() - Action string `json:"action"` //动作 - Path string `json:"path"` //路径,地址,深度 - Ip string `json:"ip"` //ip地址 - Topic string `json:"topic"` - Bundle string `json:"bundle"` - Pid string `json:"pid"` - Data interface{} `json:"data"` - Creat_time time.Time `json:"created"` -} - -/* -向es发送数据结构信息 -*/ -type EsLogInfo struct { - Info LogInfo `json:"loginfo"` //信息 - Es_index string `json:"es_index"` //索引 - Es_type string `json:"es_type"` //类型 - Es_id string `json:"es_id"` //id -} - -const ( - Http_log_index = "http_log" -) - -const mapping = ` -{ - "settings":{ - "number_of_shards": 1, - "number_of_replicas": 5 - }, - "mappings":{ - "` + Http_log_index + `":{ - "properties":{ - "service":{ - "type":"keyword" - }, - "group":{ - "type":"keyword" - }, - "type":{ - "type":"text" - }, - "action":{ - "type":"keyword" - }, - "path":{ - "type":"text" - }, - "ip":{ - "type":"text" - }, - "topic":{ - "type":"keyword" - }, - "bundle":{ - "type":"keyword" - }, - "pid":{ - "type":"keyword" - }, - "data":{ - "type":"text" - }, - "created":{ - "type":"date" - } - } - } - } -}` diff --git a/mylog/mylog.go b/mylog/mylog.go index 1569c81..43db53a 100644 --- a/mylog/mylog.go +++ b/mylog/mylog.go @@ -1,131 +1,83 @@ package mylog -import ( - "fmt" - "log" - "os" - "os/exec" - "path/filepath" - "runtime/debug" - "sync" - "time" +var _log myLog - "github.com/gookit/color" - "github.com/xxjwxc/public/dev" - "github.com/xxjwxc/public/errors" -) - -var _logerTuple logerTuple - -type logerTuple struct { - once sync.Once - _path string +func init() { + _log = GetDefaultStd() } -const ( // - logError = iota //打印 Error 及以上级别 - logwarning //打印 warning 及以上级别 - logInfo //默认的返回值,为0,自增 //打印 Info 及以上级别 -) +type myLog interface { + Debug(a ...interface{}) + Debugf(msg string, a ...interface{}) + Info(a ...interface{}) + Infof(msg string, a ...interface{}) + Error(a ...interface{}) + Errorf(msg string, a ...interface{}) + Fatal(v ...interface{}) // 系统级错误,退出 + Fatalf(msg string, a ...interface{}) // 系统级错误,退出 + SaveError(errstring, flag string) + Panic(a ...interface{}) -// Print 打印信息 -func Print(logLevel int, describ string) { - log.Println(color.Info.Render(describ)) - return + TraceError(err error) error + Close() } -// Println 打印信息 -func Println(describ ...interface{}) { - for _, e := range describ { - switch v := e.(type) { - // case string: - // log.Println(color.Info.Render(v)) - case []byte: - log.Println(color.Info.Render(string(v))) - default: - log.Println(color.Info.Render(v)) - } - } - return +// SetLog set log +func SetLog(log myLog) { + _log = log } -// Info ... -func Info(describ string) { - log.Println(color.FgGreen.Render(describ)) - return +// Info info level debug +func Info(a ...interface{}) { + _log.Info(a...) +} + +// Infof info level debug +func Infof(msg string, a ...interface{}) { + _log.Infof(msg, a...) } // Error 记录错误信息 -func Error(err error) { - err = errors.Cause(err) //获取原始对象 - log.Println(color.Error.Render(fmt.Sprintf(":Cause:%+v", err))) - SaveError(fmt.Sprintf("%+v", err), "err") +func Error(a ...interface{}) { + _log.Error(a...) } -// TraceError 追踪器 +// Errorf 记录错误信息 +func Errorf(msg string, a ...interface{}) { + _log.Errorf(msg, a...) +} + +// Debug level debug +func Debug(a ...interface{}) { + _log.Debug(a...) +} + +// Debugf level debug +func Debugf(msg string, a ...interface{}) { + _log.Debugf(msg, a...) +} + +// Fatal level fatal +func Fatal(a ...interface{}) { + _log.Fatal(a...) +} + +// Fatalf level fatal +func Fatalf(msg string, a ...interface{}) { + _log.Fatal(a...) +} + +// TraceError return trace of error func TraceError(err error) error { - Error(err) - - return errors.WithStack(err) + return _log.TraceError(err) } -// ErrorString 打印错误信息 -func ErrorString(v ...interface{}) { - log.Output(2, color.Error.Render(fmt.Sprint(v...))) -} - -//Fatalf 系统级错误 -func Fatalf(src string, v ...interface{}) { - log.Output(2, color.Error.Render(fmt.Sprintf(src, v...))) - os.Exit(1) -} - -//Fatal 系统级错误 -func Fatal(v ...interface{}) { - log.Output(2, color.Error.Render(fmt.Sprint(v...))) - os.Exit(1) -} - -func initPath() { - file, _ := exec.LookPath(os.Args[0]) - path, _ := filepath.Abs(file) - path = filepath.Dir(path) - _logerTuple._path = path + "/err" - os.MkdirAll(_logerTuple._path, os.ModePerm) //生成多级目录 -} - -// SaveError 保存错误信息 +// SaveError return trace of error func SaveError(errstring, flag string) { - _logerTuple.once.Do(initPath) - - now := time.Now() //获取当前时间 - timeStr := now.Format("2006-01-02_15") //设定时间格式 - fname := fmt.Sprintf("%s/%s_%s.log", _logerTuple._path, flag, timeStr) //保存错误信息文件名:程序名-进程ID-当前时间(年月日时分秒) - - f, err := os.OpenFile(fname, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666) - if err != nil { - return - } - defer f.Close() - - f.WriteString("=========================" + now.Format("2006-01-02 15:04:05 ========================= \r\n")) - f.WriteString(errstring + "\r\n") //输出堆栈信息 - f.WriteString(string(debug.Stack()) + "\r\n") //输出堆栈信息) - f.WriteString("=========================end=========================\r\n") + _log.SaveError(errstring, flag) } -// Debug debug -func Debug(describ ...interface{}) { - if dev.IsDev() { - for _, e := range describ { - switch v := e.(type) { - case string: - log.Println(color.Note.Render(v)) - case []byte: - log.Println(color.Note.Render(string(v))) - default: - log.Println(color.Note.Render(fmt.Sprintf("%+v", v))) - } - } - } +// Panic return trace of error +func Panic(a ...interface{}) { + _log.Panic(a...) } diff --git a/mylog/mylog_test.go b/mylog/mylog_test.go new file mode 100644 index 0000000..8f91ec0 --- /dev/null +++ b/mylog/mylog_test.go @@ -0,0 +1,48 @@ +package mylog + +import ( + "fmt" + "testing" + "time" + + "github.com/xxjwxc/public/dev" + + "github.com/xxjwxc/public/errors" +) + +func TestStdLog(t *testing.T) { + Info("aaaa") + Debug("bbbb") + Error(fmt.Errorf("nottttt")) + fmt.Println(TraceError(errors.New("wwww"))) +} + +type aaa struct { + Act string + Begin int64 +} +type ttt struct { + Act string + Begin int64 + Cat *aaa +} + +func TestZapLog(t *testing.T) { + dev.SetService("xxjwxc") + // dev.OnSetDev(true) + SetLog(GetDefaultZap()) + + Info(&ttt{ + Act: "====001===", + Begin: time.Now().Unix(), + Cat: &aaa{ + Act: "----002----", + Begin: time.Now().Unix(), + }, + }) + Info("aaaa") + Debug("bbbb") + Error(fmt.Errorf("nottttt")) + fmt.Println(TraceError(errors.New("wwww"))) + +} diff --git a/mylog/std.go b/mylog/std.go new file mode 100644 index 0000000..2ead180 --- /dev/null +++ b/mylog/std.go @@ -0,0 +1,88 @@ +package mylog + +import ( + "fmt" + "log" + "os" + + "github.com/xxjwxc/public/dev" + + "github.com/gookit/color" + "github.com/xxjwxc/public/errors" +) + +type stdLog struct { + errDeal +} + +const ( // + logError = iota //打印 Error 及以上级别 + logwarning //打印 warning 及以上级别 + logInfo //默认的返回值,为0,自增 //打印 Info 及以上级别 +) + +// GetDefaultStd get default std logger +func GetDefaultStd() *stdLog { + return &stdLog{} +} + +// Info level info msg +func (s *stdLog) Info(a ...interface{}) { + log.Println(color.FgGreen.Render(a...)) +} + +// Info level info msg +func (s *stdLog) Infof(msg string, a ...interface{}) { + log.Println(color.FgGreen.Render(fmt.Sprintf(msg, a...))) +} + +// Error 记录错误信息 +func (s *stdLog) Error(a ...interface{}) { + // err = errors.Cause(err) //获取原始对象 + log.Println(color.Error.Render(a...)) + s.SaveError(getStr(a...), "err") +} + +// Errorf 记录错误信息 +func (s *stdLog) Errorf(msg string, a ...interface{}) { + log.Println(color.Error.Render(a...)) + s.SaveError(fmt.Sprintf(msg, a...), "err") +} + +// Debug level info msg +func (s *stdLog) Debug(a ...interface{}) { + if dev.IsDev() { + log.Println(color.Debug.Render(a...)) + } +} + +// Debug level info msg +func (s *stdLog) Debugf(msg string, a ...interface{}) { + if dev.IsDev() { + log.Println(color.Debug.Render(fmt.Sprintf(msg, a...))) + } +} + +//Fatal 系统级错误 +func (s *stdLog) Fatal(a ...interface{}) { + log.Output(2, color.Error.Render(fmt.Sprint(a...))) + os.Exit(1) +} + +//Fatalf 系统级错误 +func (s *stdLog) Fatalf(msg string, a ...interface{}) { + log.Output(2, color.Error.Render(fmt.Sprintf(msg, a...))) + os.Exit(1) +} + +// TraceError return trace of error +func (s *stdLog) TraceError(err error) error { + e := errors.Cause(err) //获取原始对象 + log.Println(color.Error.Render(fmt.Sprintf(":Cause:%+v", e))) + s.SaveError(getStr(err), "err") + return errors.WithStack(err) +} + +func (s *stdLog) Close() { + +} diff --git a/mylog/zap.go b/mylog/zap.go new file mode 100644 index 0000000..38e5a44 --- /dev/null +++ b/mylog/zap.go @@ -0,0 +1,130 @@ +package mylog + +import ( + "fmt" + "os" + + "github.com/pkg/errors" + "github.com/xxjwxc/public/dev" + + "go.uber.org/zap" + "go.uber.org/zap/zapcore" + "gopkg.in/natefinch/lumberjack.v2" +) + +type zapLog struct { + logger *zap.Logger + errDeal +} + +// GetDefaultZap 获取默认zap日志库 +func GetDefaultZap() *zapLog { + hook := lumberjack.Logger{ + Filename: fmt.Sprintf("%v/log/%v.log", getCurrentDirectory(), dev.GetService()), // 日志文件路径 + MaxSize: 128, // 每个日志文件保存的最大尺寸 单位:M + MaxBackups: 30, // 日志文件最多保存多少个备份 + MaxAge: 28, // 文件最多保存多少天 + Compress: true, // 是否压缩 + } + encoderConfig := zapcore.EncoderConfig{ + TimeKey: "time", + LevelKey: "level", + NameKey: "logger", + CallerKey: "caller", + MessageKey: "msg", + StacktraceKey: "stacktrace", + LineEnding: zapcore.DefaultLineEnding, + EncodeLevel: zapcore.LowercaseLevelEncoder, // 小写编码器 + EncodeTime: zapcore.ISO8601TimeEncoder, // ISO8601 UTC 时间格式 + EncodeDuration: zapcore.SecondsDurationEncoder, // + EncodeCaller: zapcore.FullCallerEncoder, // 全路径编码器 + EncodeName: zapcore.FullNameEncoder, + } + // 设置日志级别 + atomicLevel := zap.NewAtomicLevel() + level := zap.InfoLevel + if dev.IsDev() { + level = zap.DebugLevel + } + atomicLevel.SetLevel(level) + core := zapcore.NewCore( + //zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), + zapcore.NewJSONEncoder(encoderConfig), // 编码器配置 + zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(&hook)), // 打印到控制台和文件 + atomicLevel, // 日志级别 + ) + // 开启开发模式,堆栈跟踪 + caller := zap.AddCaller() + // 开启文件及行号 + development := zap.Development() + // 设置初始化字段 + filed := zap.Fields(zap.String("service", dev.GetService())) + return &zapLog{ + logger: zap.New(core, caller, development, filed, zap.AddCallerSkip(2)), // 构造日志 + } +} + +// SetLogger set net logger +func (z *zapLog) SetLogger(logger *zap.Logger) { + z.logger = logger +} + +// Info level info msg +func (z *zapLog) Info(a ...interface{}) { + z.logger.Info(getStr(a...)) +} + +// Info level info msg +func (z *zapLog) Infof(msg string, a ...interface{}) { + z.logger.Info(fmt.Sprintf(msg, a...)) +} + +// Error 记录错误信息 +func (z *zapLog) Error(a ...interface{}) { + // err = errors.Cause(err) //获取原始对象 + z.logger.Error(getStr(a...)) + z.SaveError(getStr(a...), "err") +} + +// Errorf 记录错误信息 +func (z *zapLog) Errorf(msg string, a ...interface{}) { + z.logger.Error(fmt.Sprintf(msg, a...)) + z.SaveError(fmt.Sprintf(msg, a...), "err") +} + +// Debug level info msg +func (z *zapLog) Debug(a ...interface{}) { + if dev.IsDev() { + z.logger.Debug(getStr(a...)) + } +} + +// Debug level info msg +func (z *zapLog) Debugf(msg string, a ...interface{}) { + if dev.IsDev() { + z.logger.Debug(fmt.Sprintf(msg, a...)) + } +} + +//Fatal 系统级错误 +func (z *zapLog) Fatal(a ...interface{}) { + z.logger.Fatal(getStr(a...)) + os.Exit(1) +} + +//Fatalf 系统级错误 +func (z *zapLog) Fatalf(msg string, a ...interface{}) { + z.logger.Fatal(fmt.Sprintf(msg, a...)) + os.Exit(1) +} + +// TraceError return trace of error +func (z *zapLog) TraceError(err error) error { + e := errors.Cause(err) //获取原始对象 + z.logger.Error("Cause", zap.Error(e)) + return errors.WithStack(err) +} + +// Close close the logger +func (z *zapLog) Close() { +} diff --git a/mynsq/mynsq.go b/mynsq/mynsq.go index 1802e44..da6cfd7 100644 --- a/mynsq/mynsq.go +++ b/mynsq/mynsq.go @@ -19,7 +19,7 @@ func init() { var err error producer, err = nsq.NewProducer(config.GetNsqAddr(), cnf) if err != nil { - mylog.Print(mylog.Log_Error, err.Error()) + mylog.Error(err) panic(err) } @@ -34,7 +34,7 @@ func ProduceMsg(topic string, message []byte) bool { var err error producer, err = nsq.NewProducer(config.GetNsqAddr(), cnf) if err != nil { - mylog.Print(mylog.Log_Error, err.Error()) + mylog.Error(err) return false } } @@ -42,7 +42,7 @@ func ProduceMsg(topic string, message []byte) bool { if producer != nil { err := producer.Publish(topic, message) if err != nil { - mylog.Print(mylog.Log_Error, err.Error()) + mylog.Error(err) return false } else { return true @@ -65,7 +65,7 @@ func StartConsumeMsg(index int, topic, channel, nsqd string, handler nsq.Handler consumerMap[index], err = nsq.NewConsumer(topic, channel, conf) if nil != err { log.Println(err) - mylog.Print(mylog.Log_Error, err.Error()) + mylog.Error(err) return false } @@ -74,7 +74,7 @@ func StartConsumeMsg(index int, topic, channel, nsqd string, handler nsq.Handler err = consumerMap[index].ConnectToNSQD(nsqd) if nil != err { log.Println(err) - mylog.Print(mylog.Log_Error, err.Error()) + mylog.Error(err) return false } diff --git a/mywebsocket/mywebsocket.go b/mywebsocket/mywebsocket.go index dbb2646..b30e86f 100644 --- a/mywebsocket/mywebsocket.go +++ b/mywebsocket/mywebsocket.go @@ -139,7 +139,7 @@ func InitWebSocket(pathExp string, handlerFunc HandlerReadFunc, stateFunc Handle goto loop } case <-after: //超时处理 - mylog.Print(mylog.Log_Info, "time out:"+clientid) + mylog.Info("time out:" + clientid) ws.Close() break } diff --git a/tools/convert.go b/tools/convert.go index add027e..b068e22 100644 --- a/tools/convert.go +++ b/tools/convert.go @@ -53,7 +53,6 @@ func AsString(src interface{}) string { default: { b, _ := json.Marshal(v) - mylog.Println(string(b)) return string(b) } } diff --git a/tools/ip.go b/tools/ip.go index b6ee465..872b340 100644 --- a/tools/ip.go +++ b/tools/ip.go @@ -10,28 +10,6 @@ import ( "github.com/xxjwxc/public/mylog" ) -///* -// 获取外网ip -//*/ -//func GetWwwIP() (ip string) { -// ip = "" -// resp, err := http.Get("http://myexternalip.com/raw") -// if err != nil { -// mylog.Error(err) -// return -// } - -// defer resp.Body.Close() -// body, err := ioutil.ReadAll(resp.Body) -// if err != nil { -// return -// } - -// ip = string(body) -// ip = strings.Split(ip, "\n")[0] -// return -//} - // GetWwwIP 获取公网IP地址 func GetWwwIP() (exip string) { resp, err := http.Get("http://myexternalip.com/raw")