This commit is contained in:
谢小军
2020-06-03 19:58:33 +08:00
parent ab2b4ce31a
commit 341beff278
17 changed files with 442 additions and 253 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

View File

@@ -1,3 +0,0 @@
{
"go.inferGopath": false
}

4
go.mod
View File

@@ -26,13 +26,15 @@ require (
github.com/nsf/termbox-go v0.0.0-20200418040025-38ba6e5628f1 // indirect github.com/nsf/termbox-go v0.0.0-20200418040025-38ba6e5628f1 // indirect
github.com/nsqio/go-nsq v1.0.8 github.com/nsqio/go-nsq v1.0.8
github.com/olivere/elastic v6.2.31+incompatible 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/spf13/cobra v1.0.0
github.com/syndtr/goleveldb 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/crypto v0.0.0-20191205180655-e7c4368fe9dd
golang.org/x/image v0.0.0-20200430140353-33d19683fad8 // indirect golang.org/x/image v0.0.0-20200430140353-33d19683fad8 // indirect
golang.org/x/net v0.0.0-20200506145744-7e3656a0809f golang.org/x/net v0.0.0-20200506145744-7e3656a0809f
golang.org/x/text v0.3.2 golang.org/x/text v0.3.2
gopkg.in/eapache/queue.v1 v1.1.0 gopkg.in/eapache/queue.v1 v1.1.0
gopkg.in/go-with/wxpay.v1 v1.3.0 gopkg.in/go-with/wxpay.v1 v1.3.0
gopkg.in/natefinch/lumberjack.v2 v2.0.0
) )

5
go.sum
View File

@@ -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/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= 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.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/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/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= 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-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 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/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 h1:RXVQck9qNIGkajbTMCvlRPHeewyAIItzOybTTykVdV0=
gopkg.in/go-with/wxpay.v1 v1.3.0/go.mod h1:12lWy92n19pAUSSE3BrOiEZbWRkl+9tneOd/aU/LU6g= 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/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 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=

View File

@@ -10,13 +10,12 @@ package mycatch
import ( import (
"fmt" "fmt"
"os"
"runtime/debug" "runtime/debug"
"time"
"github.com/xxjwxc/public/tools" "github.com/xxjwxc/public/mylog"
) )
// Dmp dmp the recover
func Dmp() { func Dmp() {
errstr := "" errstr := ""
if err := recover(); err != nil { if err := recover(); err != nil {
@@ -25,28 +24,29 @@ func Dmp() {
} }
errstr += (string(debug.Stack())) //输出堆栈信息 errstr += (string(debug.Stack())) //输出堆栈信息
OnPrintErr(errstr) mylog.Panic(errstr, "err")
// OnPrintErr(errstr)
} }
func OnPrintErr(errstring string) { // func OnPrintErr(errstring string) {
path := tools.GetCurrentDirectory() + "/err" // path := tools.GetCurrentDirectory() + "/err"
if !tools.CheckFileIsExist(path) { // if !tools.CheckFileIsExist(path) {
os.MkdirAll(path, os.ModePerm) //生成多级目录 // os.MkdirAll(path, os.ModePerm) //生成多级目录
} // }
now := time.Now() //获取当前时间 // now := time.Now() //获取当前时间
pid := os.Getpid() //获取进程ID // pid := os.Getpid() //获取进程ID
time_str := now.Format("2006-01-02") //设定时间格式 // timeStr := now.Format("2006-01-02") //设定时间格式
fname := fmt.Sprintf("%s/panic_%s-%x.log", path, time_str, pid) //保存错误信息文件名:程序名-进程ID-当前时间(年月日时分秒) // fname := fmt.Sprintf("%s/panic_%s-%x.log", path, timeStr, pid) //保存错误信息文件名:程序名-进程ID-当前时间(年月日时分秒)
fmt.Println("panic to file ", fname) // fmt.Println("panic to file ", fname)
f, err := os.OpenFile(fname, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666) // f, err := os.OpenFile(fname, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
if err != nil { // if err != nil {
return // return
} // }
defer f.Close() // defer f.Close()
f.WriteString("=========================" + now.Format("2006-01-02 15:04:05 ========================= \r\n")) // f.WriteString("=========================" + now.Format("2006-01-02 15:04:05 ========================= \r\n"))
f.WriteString(errstring) //输出堆栈信息 // f.WriteString(errstring) //输出堆栈信息
f.WriteString("=========================end=========================") // f.WriteString("=========================end=========================")
} // }

View File

@@ -95,7 +95,7 @@ func (this *HDC) DrawText(pen Pen, text string) bool {
for _, s := range strings.Split(text, "\r\n") { for _, s := range strings.Split(text, "\r\n") {
_, err := c.DrawString(s, pt) _, err := c.DrawString(s, pt)
if err != nil { if err != nil {
mylog.Println("c.DrawString(%s) error(%v)", s, err) mylog.Infof("c.DrawString(%s) error(%v)", s, err)
return false return false
} }
pt.Y += c.PointToFixed(pen.FontSize * 1.5) 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) err = jpeg.Encode(output, this.Rgba, nil)
} }
if err != nil { if err != nil {
mylog.Infof("image encode error(%v)", err)
mylog.Println("image encode error(%v)", err)
//mylog.Error(err)
return false return false
} }
return true return true

View File

@@ -37,7 +37,7 @@ func OnInitES(url string) MyElastic {
//func (es *MyElastic) Model(refs interface{}) *MyElastic { //func (es *MyElastic) Model(refs interface{}) *MyElastic {
// if reflect.ValueOf(refs).Type().Kind() != reflect.Ptr { // 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) // panic(0)
// } // }

75
mylog/common.go Normal file
View File

@@ -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...)
}

View File

@@ -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"
}
}
}
}
}`

View File

@@ -1,131 +1,83 @@
package mylog package mylog
import ( var _log myLog
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"runtime/debug"
"sync"
"time"
"github.com/gookit/color" func init() {
"github.com/xxjwxc/public/dev" _log = GetDefaultStd()
"github.com/xxjwxc/public/errors"
)
var _logerTuple logerTuple
type logerTuple struct {
once sync.Once
_path string
} }
const ( // type myLog interface {
logError = iota //打印 Error 及以上级别 Debug(a ...interface{})
logwarning //打印 warning 及以上级别 Debugf(msg string, a ...interface{})
logInfo //默认的返回值为0自增 //打印 Info 及以上级别 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 打印信息 TraceError(err error) error
func Print(logLevel int, describ string) { Close()
log.Println(color.Info.Render(describ))
return
} }
// Println 打印信息 // SetLog set log
func Println(describ ...interface{}) { func SetLog(log myLog) {
for _, e := range describ { _log = log
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
} }
// Info ... // Info info level debug
func Info(describ string) { func Info(a ...interface{}) {
log.Println(color.FgGreen.Render(describ)) _log.Info(a...)
return }
// Infof info level debug
func Infof(msg string, a ...interface{}) {
_log.Infof(msg, a...)
} }
// Error 记录错误信息 // Error 记录错误信息
func Error(err error) { func Error(a ...interface{}) {
err = errors.Cause(err) //获取原始对象 _log.Error(a...)
log.Println(color.Error.Render(fmt.Sprintf(":Cause:%+v", err)))
SaveError(fmt.Sprintf("%+v", err), "err")
} }
// 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 { func TraceError(err error) error {
Error(err) return _log.TraceError(err)
return errors.WithStack(err)
} }
// ErrorString 打印错误信息 // SaveError return trace of error
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 保存错误信息
func SaveError(errstring, flag string) { func SaveError(errstring, flag string) {
_logerTuple.once.Do(initPath) _log.SaveError(errstring, flag)
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")
} }
// Debug debug // Panic return trace of error
func Debug(describ ...interface{}) { func Panic(a ...interface{}) {
if dev.IsDev() { _log.Panic(a...)
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)))
}
}
}
} }

48
mylog/mylog_test.go Normal file
View File

@@ -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")))
}

88
mylog/std.go Normal file
View File

@@ -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() {
}

130
mylog/zap.go Normal file
View File

@@ -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() {
}

View File

@@ -19,7 +19,7 @@ func init() {
var err error var err error
producer, err = nsq.NewProducer(config.GetNsqAddr(), cnf) producer, err = nsq.NewProducer(config.GetNsqAddr(), cnf)
if err != nil { if err != nil {
mylog.Print(mylog.Log_Error, err.Error()) mylog.Error(err)
panic(err) panic(err)
} }
@@ -34,7 +34,7 @@ func ProduceMsg(topic string, message []byte) bool {
var err error var err error
producer, err = nsq.NewProducer(config.GetNsqAddr(), cnf) producer, err = nsq.NewProducer(config.GetNsqAddr(), cnf)
if err != nil { if err != nil {
mylog.Print(mylog.Log_Error, err.Error()) mylog.Error(err)
return false return false
} }
} }
@@ -42,7 +42,7 @@ func ProduceMsg(topic string, message []byte) bool {
if producer != nil { if producer != nil {
err := producer.Publish(topic, message) err := producer.Publish(topic, message)
if err != nil { if err != nil {
mylog.Print(mylog.Log_Error, err.Error()) mylog.Error(err)
return false return false
} else { } else {
return true 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) consumerMap[index], err = nsq.NewConsumer(topic, channel, conf)
if nil != err { if nil != err {
log.Println(err) log.Println(err)
mylog.Print(mylog.Log_Error, err.Error()) mylog.Error(err)
return false return false
} }
@@ -74,7 +74,7 @@ func StartConsumeMsg(index int, topic, channel, nsqd string, handler nsq.Handler
err = consumerMap[index].ConnectToNSQD(nsqd) err = consumerMap[index].ConnectToNSQD(nsqd)
if nil != err { if nil != err {
log.Println(err) log.Println(err)
mylog.Print(mylog.Log_Error, err.Error()) mylog.Error(err)
return false return false
} }

View File

@@ -139,7 +139,7 @@ func InitWebSocket(pathExp string, handlerFunc HandlerReadFunc, stateFunc Handle
goto loop goto loop
} }
case <-after: //超时处理 case <-after: //超时处理
mylog.Print(mylog.Log_Info, "time out:"+clientid) mylog.Info("time out:" + clientid)
ws.Close() ws.Close()
break break
} }

View File

@@ -53,7 +53,6 @@ func AsString(src interface{}) string {
default: default:
{ {
b, _ := json.Marshal(v) b, _ := json.Marshal(v)
mylog.Println(string(b))
return string(b) return string(b)
} }
} }

View File

@@ -10,28 +10,6 @@ import (
"github.com/xxjwxc/public/mylog" "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地址 // GetWwwIP 获取公网IP地址
func GetWwwIP() (exip string) { func GetWwwIP() (exip string) {
resp, err := http.Get("http://myexternalip.com/raw") resp, err := http.Get("http://myexternalip.com/raw")