92 lines
1.7 KiB
Go
92 lines
1.7 KiB
Go
package logger
|
|
|
|
import (
|
|
"energy-management-system/global"
|
|
"fmt"
|
|
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
|
|
"github.com/sirupsen/logrus"
|
|
"runtime"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
func InitLogger() *global.Logger {
|
|
L := logrus.New()
|
|
path := "./log/log"
|
|
file, _ := rotatelogs.New(
|
|
path+".%Y%m%d",
|
|
rotatelogs.WithLinkName(path),
|
|
rotatelogs.WithMaxAge(time.Duration(100*24)*time.Hour), //自动删除
|
|
rotatelogs.WithRotationTime(time.Duration(24*60)*time.Minute), //分割时间
|
|
)
|
|
L.SetOutput(file)
|
|
L.SetFormatter(&logrus.JSONFormatter{})
|
|
Log := &global.Logger{Logger: L, Heads: []string{}}
|
|
global.Log = Log
|
|
return Log
|
|
}
|
|
|
|
var errs = &errFunc{lock: new(sync.Mutex)}
|
|
|
|
func ErrorRegister(f func(string)) {
|
|
errs.register(f, false)
|
|
}
|
|
func ErrorRegisterOnly1(f func(string)) {
|
|
errs.register(f, true)
|
|
}
|
|
func ErrorWx(e ...string) {
|
|
errs.run(strings.Join(e, " "))
|
|
global.Log.Error(e)
|
|
}
|
|
|
|
type errFunc struct {
|
|
f []func(string)
|
|
lastTime int64
|
|
lock *sync.Mutex
|
|
}
|
|
|
|
func (e *errFunc) register(f func(string), only bool) {
|
|
if only {
|
|
e.f = []func(string){f}
|
|
} else {
|
|
e.f = append(e.f, f)
|
|
}
|
|
}
|
|
|
|
func (e *errFunc) run(logs string) {
|
|
if len(e.f) == 0 {
|
|
return
|
|
}
|
|
if time.Now().Unix()-e.lastTime > 1 {
|
|
e.lock.Lock()
|
|
e.lastTime = time.Now().Unix()
|
|
defer e.lock.Unlock()
|
|
for _, v := range e.f {
|
|
v(logs)
|
|
}
|
|
}
|
|
}
|
|
|
|
func StackSend(skip int, e string) {
|
|
e += "\n" + Stack(skip)
|
|
if global.AppConf.IsDebug {
|
|
fmt.Print(e)
|
|
}
|
|
errs.run(e)
|
|
}
|
|
|
|
func Stack(skip int) (re string) {
|
|
for i := skip; ; i++ {
|
|
_, file, line, ok := runtime.Caller(i)
|
|
if !ok {
|
|
break
|
|
}
|
|
if !strings.Contains(file, "local/go/src") && !strings.Contains(file, "/go/pkg") {
|
|
logs := fmt.Sprintf("%s:%d\n", file, line)
|
|
re += logs
|
|
}
|
|
}
|
|
return
|
|
}
|