mirror of
https://github.com/openimsdk/open-im-server.git
synced 2026-05-12 04:55:59 +08:00
feat: use robot to migrate code
Signed-off-by: kubbot & kubecub <3293172751ysy@gmail.com>
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
// Foreground colors.
|
||||
const (
|
||||
Black Color = iota + 30
|
||||
Red
|
||||
Green
|
||||
Yellow
|
||||
Blue
|
||||
Magenta
|
||||
Cyan
|
||||
White
|
||||
)
|
||||
|
||||
var (
|
||||
_levelToColor = map[zapcore.Level]Color{
|
||||
zapcore.DebugLevel: White,
|
||||
zapcore.InfoLevel: Blue,
|
||||
zapcore.WarnLevel: Yellow,
|
||||
zapcore.ErrorLevel: Red,
|
||||
zapcore.DPanicLevel: Red,
|
||||
zapcore.PanicLevel: Red,
|
||||
zapcore.FatalLevel: Red,
|
||||
}
|
||||
_unknownLevelColor = make(map[zapcore.Level]string, len(_levelToColor))
|
||||
|
||||
_levelToLowercaseColorString = make(map[zapcore.Level]string, len(_levelToColor))
|
||||
_levelToCapitalColorString = make(map[zapcore.Level]string, len(_levelToColor))
|
||||
)
|
||||
|
||||
func init() {
|
||||
for level, color := range _levelToColor {
|
||||
_levelToLowercaseColorString[level] = color.Add(level.String())
|
||||
_levelToCapitalColorString[level] = color.Add(level.CapitalString())
|
||||
}
|
||||
}
|
||||
|
||||
// Color represents a text color.
|
||||
type Color uint8
|
||||
|
||||
// Add adds the coloring to the given string.
|
||||
func (c Color) Add(s string) string {
|
||||
return fmt.Sprintf("\x1b[%dm%s\x1b[0m", uint8(c), s)
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
/*
|
||||
** description("Send logs to elasticsearch hook").
|
||||
** copyright('tuoyun,www.tuoyun.net').
|
||||
** author("fg,Gordon@tuoyun.net").
|
||||
** time(2021/3/26 17:05).
|
||||
*/
|
||||
package log
|
||||
|
||||
import (
|
||||
"Open_IM/pkg/common/config"
|
||||
"context"
|
||||
"fmt"
|
||||
elasticV7 "github.com/olivere/elastic/v7"
|
||||
"github.com/sirupsen/logrus"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
//esHook CUSTOMIZED ES hook
|
||||
type esHook struct {
|
||||
moduleName string
|
||||
client *elasticV7.Client
|
||||
}
|
||||
|
||||
//newEsHook Initialization
|
||||
func newEsHook(moduleName string) *esHook {
|
||||
//https://github.com/sohlich/elogrus
|
||||
//client, err := elastic.NewClient(elastic.SetURL("http://localhost:9200"))
|
||||
//if err != nil {
|
||||
// log.Panic(err)
|
||||
//}
|
||||
//hook, err := elogrus.NewAsyncElasticHook(client, "localhost", logrus.DebugLevel, "mylog")
|
||||
//if err != nil {
|
||||
// log.Panic(err)
|
||||
//}
|
||||
es, err := elasticV7.NewClient(
|
||||
elasticV7.SetURL(config.Config.Log.ElasticSearchAddr...),
|
||||
elasticV7.SetBasicAuth(config.Config.Log.ElasticSearchUser, config.Config.Log.ElasticSearchPassword),
|
||||
elasticV7.SetSniff(false),
|
||||
elasticV7.SetHealthcheckInterval(60*time.Second),
|
||||
elasticV7.SetErrorLog(log.New(os.Stderr, "ES:", log.LstdFlags)),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
log.Fatal("failed to create Elastic V7 Client: ", err)
|
||||
}
|
||||
|
||||
//info, code, err := es.Ping(logConfig.ElasticSearch.EsAddr[0]).Do(context.Background())
|
||||
//if err != nil {
|
||||
// panic(err)
|
||||
//}
|
||||
//fmt.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)
|
||||
//
|
||||
//esversion, err := es.ElasticsearchVersion(logConfig.ElasticSearch.EsAddr[0])
|
||||
//if err != nil {
|
||||
// panic(err)
|
||||
//}
|
||||
//fmt.Printf("Elasticsearch version %s\n", esversion)
|
||||
return &esHook{client: es, moduleName: moduleName}
|
||||
}
|
||||
|
||||
//Fire log hook interface
|
||||
func (hook *esHook) Fire(entry *logrus.Entry) error {
|
||||
doc := newEsLog(entry)
|
||||
go hook.sendEs(doc)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hook *esHook) Levels() []logrus.Level {
|
||||
return logrus.AllLevels
|
||||
}
|
||||
|
||||
//sendEs
|
||||
func (hook *esHook) sendEs(doc appLogDocModel) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
fmt.Println("send entry to es failed: ", r)
|
||||
}
|
||||
}()
|
||||
_, err := hook.client.Index().Index(hook.moduleName).Type(doc.indexName()).BodyJson(doc).Do(context.Background())
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//appLogDocModel es model
|
||||
type appLogDocModel map[string]interface{}
|
||||
|
||||
func newEsLog(e *logrus.Entry) appLogDocModel {
|
||||
ins := make(map[string]interface{})
|
||||
ins["level"] = strings.ToUpper(e.Level.String())
|
||||
ins["time"] = e.Time.Format("2006-01-02 15:04:05")
|
||||
for kk, vv := range e.Data {
|
||||
ins[kk] = vv
|
||||
}
|
||||
ins["tipInfo"] = e.Message
|
||||
|
||||
return ins
|
||||
}
|
||||
|
||||
// indexName es index name
|
||||
func (m *appLogDocModel) indexName() string {
|
||||
return time.Now().Format("2006-01-02")
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
/*
|
||||
** description("get the name and line number of the calling file hook").
|
||||
** copyright('tuoyun,www.tuoyun.net').
|
||||
** author("fg,Gordon@tuoyun.net").
|
||||
** time(2021/3/16 11:26).
|
||||
*/
|
||||
package log
|
||||
|
||||
import (
|
||||
"Open_IM/pkg/utils"
|
||||
"github.com/sirupsen/logrus"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type fileHook struct{}
|
||||
|
||||
func newFileHook() *fileHook {
|
||||
return &fileHook{}
|
||||
}
|
||||
|
||||
func (f *fileHook) Levels() []logrus.Level {
|
||||
return logrus.AllLevels
|
||||
}
|
||||
|
||||
//func (f *fileHook) Fire(entry *logrus.Entry) error {
|
||||
// entry.Data["FilePath"] = findCaller(6)
|
||||
// utils.GetSelfFuncName()
|
||||
// return nil
|
||||
//}
|
||||
|
||||
func (f *fileHook) Fire(entry *logrus.Entry) error {
|
||||
var s string
|
||||
_, file, line, _ := runtime.Caller(8)
|
||||
i := strings.SplitAfter(file, "/")
|
||||
if len(i) > 3 {
|
||||
s = i[len(i)-3] + i[len(i)-2] + i[len(i)-1] + ":" + utils.IntToString(line)
|
||||
}
|
||||
entry.Data["FilePath"] = s
|
||||
return nil
|
||||
}
|
||||
|
||||
//func findCaller(skip int) string {
|
||||
// file := ""
|
||||
// line := 0
|
||||
// for i := 0; i < 10; i++ {
|
||||
// file, line = getCaller(skip + i)
|
||||
// if !strings.HasPrefix(file, "log") {
|
||||
// break
|
||||
// }
|
||||
// }
|
||||
// return fmt.Sprintf("%s:%d", file, line)
|
||||
//}
|
||||
//
|
||||
//func getCaller(skip int) (string, int) {
|
||||
// _, file, line, ok := runtime.Caller(skip)
|
||||
//
|
||||
// if !ok {
|
||||
// return "", 0
|
||||
// }
|
||||
// fmt.Println("skip:", skip, "file:", file, "line", line)
|
||||
// n := 0
|
||||
// for i := len(file) - 1; i > 0; i-- {
|
||||
// if file[i] == '/' {
|
||||
// n++
|
||||
// if n >= 2 {
|
||||
// file = file[i+1:]
|
||||
// break
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// return file, line
|
||||
//}
|
||||
@@ -0,0 +1,13 @@
|
||||
package log
|
||||
|
||||
import "context"
|
||||
|
||||
type Logger interface {
|
||||
Debug(ctx context.Context, msg string, keysAndValues ...interface{})
|
||||
Info(ctx context.Context, msg string, keysAndValues ...interface{})
|
||||
Warn(ctx context.Context, msg string, err error, keysAndValues ...interface{})
|
||||
Error(ctx context.Context, msg string, err error, keysAndValues ...interface{})
|
||||
WithValues(keysAndValues ...interface{}) Logger
|
||||
WithName(name string) Logger
|
||||
WithCallDepth(depth int) Logger
|
||||
}
|
||||
@@ -1,200 +0,0 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"Open_IM/pkg/common/config"
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
nested "github.com/antonfisher/nested-logrus-formatter"
|
||||
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
|
||||
"github.com/rifflock/lfshook"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var logger *Logger
|
||||
|
||||
type Logger struct {
|
||||
*logrus.Logger
|
||||
Pid int
|
||||
}
|
||||
|
||||
func init() {
|
||||
logger = loggerInit("")
|
||||
|
||||
}
|
||||
func NewPrivateLog(moduleName string) {
|
||||
logger = loggerInit(moduleName)
|
||||
}
|
||||
|
||||
func loggerInit(moduleName string) *Logger {
|
||||
var logger = logrus.New()
|
||||
//All logs will be printed
|
||||
logger.SetLevel(logrus.Level(config.Config.Log.RemainLogLevel))
|
||||
//Close std console output
|
||||
//os.O_WRONLY | os.O_CREATE | os.O_APPEND
|
||||
src, err := os.OpenFile(os.DevNull, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
writer := bufio.NewWriter(src)
|
||||
logger.SetOutput(writer)
|
||||
//logger.SetOutput(os.Stdout)
|
||||
//Log Console Print Style Setting
|
||||
logger.SetFormatter(&nested.Formatter{
|
||||
TimestampFormat: "2006-01-02 15:04:05.000",
|
||||
HideKeys: false,
|
||||
FieldsOrder: []string{"PID", "FilePath", "OperationID"},
|
||||
})
|
||||
//File name and line number display hook
|
||||
logger.AddHook(newFileHook())
|
||||
|
||||
//Send logs to elasticsearch hook
|
||||
if config.Config.Log.ElasticSearchSwitch {
|
||||
logger.AddHook(newEsHook(moduleName))
|
||||
}
|
||||
//Log file segmentation hook
|
||||
hook := NewLfsHook(time.Duration(config.Config.Log.RotationTime)*time.Hour, config.Config.Log.RemainRotationCount, moduleName)
|
||||
logger.AddHook(hook)
|
||||
return &Logger{
|
||||
logger,
|
||||
os.Getpid(),
|
||||
}
|
||||
}
|
||||
func NewLfsHook(rotationTime time.Duration, maxRemainNum uint, moduleName string) logrus.Hook {
|
||||
lfsHook := lfshook.NewHook(lfshook.WriterMap{
|
||||
logrus.DebugLevel: initRotateLogs(rotationTime, maxRemainNum, "all", moduleName),
|
||||
logrus.InfoLevel: initRotateLogs(rotationTime, maxRemainNum, "all", moduleName),
|
||||
logrus.WarnLevel: initRotateLogs(rotationTime, maxRemainNum, "all", moduleName),
|
||||
logrus.ErrorLevel: initRotateLogs(rotationTime, maxRemainNum, "all", moduleName),
|
||||
}, &nested.Formatter{
|
||||
TimestampFormat: "2006-01-02 15:04:05.000",
|
||||
HideKeys: false,
|
||||
FieldsOrder: []string{"PID", "FilePath", "OperationID"},
|
||||
})
|
||||
return lfsHook
|
||||
}
|
||||
func initRotateLogs(rotationTime time.Duration, maxRemainNum uint, level string, moduleName string) *rotatelogs.RotateLogs {
|
||||
if moduleName != "" {
|
||||
moduleName = moduleName + "."
|
||||
}
|
||||
writer, err := rotatelogs.New(
|
||||
config.Config.Log.StorageLocation+moduleName+level+"."+"%Y-%m-%d",
|
||||
rotatelogs.WithRotationTime(rotationTime),
|
||||
rotatelogs.WithRotationCount(maxRemainNum),
|
||||
)
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
} else {
|
||||
return writer
|
||||
}
|
||||
}
|
||||
|
||||
func Info(OperationID string, args ...interface{}) {
|
||||
logger.WithFields(logrus.Fields{
|
||||
"OperationID": OperationID,
|
||||
"PID": logger.Pid,
|
||||
}).Infoln(args)
|
||||
}
|
||||
|
||||
func Error(OperationID string, args ...interface{}) {
|
||||
logger.WithFields(logrus.Fields{
|
||||
"OperationID": OperationID,
|
||||
"PID": logger.Pid,
|
||||
}).Errorln(args)
|
||||
}
|
||||
|
||||
func Debug(OperationID string, args ...interface{}) {
|
||||
logger.WithFields(logrus.Fields{
|
||||
"OperationID": OperationID,
|
||||
"PID": logger.Pid,
|
||||
}).Debugln(args)
|
||||
}
|
||||
|
||||
//Deprecated
|
||||
func Warning(token, OperationID, format string, args ...interface{}) {
|
||||
logger.WithFields(logrus.Fields{
|
||||
"PID": logger.Pid,
|
||||
"OperationID": OperationID,
|
||||
}).Warningf(format, args...)
|
||||
|
||||
}
|
||||
|
||||
//Deprecated
|
||||
func InfoByArgs(format string, args ...interface{}) {
|
||||
logger.WithFields(logrus.Fields{}).Infof(format, args)
|
||||
}
|
||||
|
||||
//Deprecated
|
||||
func ErrorByArgs(format string, args ...interface{}) {
|
||||
logger.WithFields(logrus.Fields{}).Errorf(format, args...)
|
||||
}
|
||||
|
||||
//Print log information in k, v format,
|
||||
//kv is best to appear in pairs. tipInfo is the log prompt information for printing,
|
||||
//and kv is the key and value for printing.
|
||||
//Deprecated
|
||||
func InfoByKv(tipInfo, OperationID string, args ...interface{}) {
|
||||
fields := make(logrus.Fields)
|
||||
argsHandle(OperationID, fields, args)
|
||||
logger.WithFields(fields).Info(tipInfo)
|
||||
}
|
||||
|
||||
//Deprecated
|
||||
func ErrorByKv(tipInfo, OperationID string, args ...interface{}) {
|
||||
fields := make(logrus.Fields)
|
||||
argsHandle(OperationID, fields, args)
|
||||
logger.WithFields(fields).Error(tipInfo)
|
||||
}
|
||||
|
||||
//Deprecated
|
||||
func DebugByKv(tipInfo, OperationID string, args ...interface{}) {
|
||||
fields := make(logrus.Fields)
|
||||
argsHandle(OperationID, fields, args)
|
||||
logger.WithFields(fields).Debug(tipInfo)
|
||||
}
|
||||
|
||||
//Deprecated
|
||||
func WarnByKv(tipInfo, OperationID string, args ...interface{}) {
|
||||
fields := make(logrus.Fields)
|
||||
argsHandle(OperationID, fields, args)
|
||||
logger.WithFields(fields).Warn(tipInfo)
|
||||
}
|
||||
|
||||
//internal method
|
||||
func argsHandle(OperationID string, fields logrus.Fields, args []interface{}) {
|
||||
for i := 0; i < len(args); i += 2 {
|
||||
if i+1 < len(args) {
|
||||
fields[fmt.Sprintf("%v", args[i])] = args[i+1]
|
||||
} else {
|
||||
fields[fmt.Sprintf("%v", args[i])] = ""
|
||||
}
|
||||
}
|
||||
fields["OperationID"] = OperationID
|
||||
fields["PID"] = logger.Pid
|
||||
}
|
||||
func NewInfo(OperationID string, args ...interface{}) {
|
||||
logger.WithFields(logrus.Fields{
|
||||
"OperationID": OperationID,
|
||||
"PID": logger.Pid,
|
||||
}).Infoln(args)
|
||||
}
|
||||
func NewError(OperationID string, args ...interface{}) {
|
||||
logger.WithFields(logrus.Fields{
|
||||
"OperationID": OperationID,
|
||||
"PID": logger.Pid,
|
||||
}).Errorln(args)
|
||||
}
|
||||
func NewDebug(OperationID string, args ...interface{}) {
|
||||
logger.WithFields(logrus.Fields{
|
||||
"OperationID": OperationID,
|
||||
"PID": logger.Pid,
|
||||
}).Debugln(args)
|
||||
}
|
||||
func NewWarn(OperationID string, args ...interface{}) {
|
||||
logger.WithFields(logrus.Fields{
|
||||
"OperationID": OperationID,
|
||||
"PID": logger.Pid,
|
||||
}).Warnln(args)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
gormLogger "gorm.io/gorm/logger"
|
||||
gormUtils "gorm.io/gorm/utils"
|
||||
)
|
||||
|
||||
type SqlLogger struct {
|
||||
LogLevel gormLogger.LogLevel
|
||||
IgnoreRecordNotFoundError bool
|
||||
SlowThreshold time.Duration
|
||||
}
|
||||
|
||||
func NewSqlLogger(logLevel gormLogger.LogLevel, ignoreRecordNotFoundError bool, slowThreshold time.Duration) *SqlLogger {
|
||||
return &SqlLogger{
|
||||
LogLevel: logLevel,
|
||||
IgnoreRecordNotFoundError: ignoreRecordNotFoundError,
|
||||
SlowThreshold: slowThreshold,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *SqlLogger) LogMode(logLevel gormLogger.LogLevel) gormLogger.Interface {
|
||||
newLogger := *l
|
||||
newLogger.LogLevel = logLevel
|
||||
return &newLogger
|
||||
}
|
||||
|
||||
func (SqlLogger) Info(ctx context.Context, msg string, args ...interface{}) {
|
||||
ZInfo(ctx, msg, args)
|
||||
}
|
||||
|
||||
func (SqlLogger) Warn(ctx context.Context, msg string, args ...interface{}) {
|
||||
ZWarn(ctx, msg, nil, args)
|
||||
}
|
||||
|
||||
func (SqlLogger) Error(ctx context.Context, msg string, args ...interface{}) {
|
||||
ZError(ctx, msg, nil, args)
|
||||
}
|
||||
|
||||
func (l *SqlLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
|
||||
if l.LogLevel <= gormLogger.Silent {
|
||||
return
|
||||
}
|
||||
elapsed := time.Since(begin)
|
||||
switch {
|
||||
case err != nil && l.LogLevel >= gormLogger.Error && (!errors.Is(err, gorm.ErrRecordNotFound) || !l.IgnoreRecordNotFoundError):
|
||||
sql, rows := fc()
|
||||
if rows == -1 {
|
||||
ZError(ctx, "sql exec detail", err, "gorm", gormUtils.FileWithLineNum(), "elapsed time", fmt.Sprintf("%f(ms)", float64(elapsed.Nanoseconds())/1e6), "sql", sql)
|
||||
} else {
|
||||
ZError(ctx, "sql exec detail", err, "gorm", gormUtils.FileWithLineNum(), "elapsed time", fmt.Sprintf("%f(ms)", float64(elapsed.Nanoseconds())/1e6), "rows", rows, "sql", sql)
|
||||
}
|
||||
case elapsed > l.SlowThreshold && l.SlowThreshold != 0 && l.LogLevel >= gormLogger.Warn:
|
||||
sql, rows := fc()
|
||||
slowLog := fmt.Sprintf("SLOW SQL >= %v", l.SlowThreshold)
|
||||
if rows == -1 {
|
||||
ZWarn(ctx, "sql exec detail", nil, "gorm", gormUtils.FileWithLineNum(), nil, "slow sql", slowLog, "elapsed time", fmt.Sprintf("%f(ms)", float64(elapsed.Nanoseconds())/1e6), "sql", sql)
|
||||
} else {
|
||||
ZWarn(ctx, "sql exec detail", nil, "gorm", gormUtils.FileWithLineNum(), nil, "slow sql", slowLog, "elapsed time", fmt.Sprintf("%f(ms)", float64(elapsed.Nanoseconds())/1e6), "rows", rows, "sql", sql)
|
||||
}
|
||||
case l.LogLevel == gormLogger.Info:
|
||||
sql, rows := fc()
|
||||
if rows == -1 {
|
||||
ZDebug(ctx, "sql exec detail", "gorm", gormUtils.FileWithLineNum(), "elapsed time", fmt.Sprintf("%f(ms)", float64(elapsed.Nanoseconds())/1e6), "sql", sql)
|
||||
} else {
|
||||
ZDebug(ctx, "sql exec detail", "gorm", gormUtils.FileWithLineNum(), "elapsed time", fmt.Sprintf("%f(ms)", float64(elapsed.Nanoseconds())/1e6), "rows", rows, "sql", sql)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
/*
|
||||
** description("").
|
||||
** copyright('tuoyun,www.tuoyun.net').
|
||||
** author("fg,Gordon@tuoyun.net").
|
||||
** time(2021/2/22 11:52).
|
||||
*/
|
||||
package log
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
TimeOffset = 8 * 3600 //8 hour offset
|
||||
HalfOffset = 12 * 3600 //Half-day hourly offset
|
||||
)
|
||||
|
||||
//Get the current timestamp
|
||||
func GetCurrentTimestamp() int64 {
|
||||
return time.Now().Unix()
|
||||
}
|
||||
|
||||
//Get the current 0 o'clock timestamp
|
||||
func GetCurDayZeroTimestamp() int64 {
|
||||
timeStr := time.Now().Format("2006-01-02")
|
||||
t, _ := time.Parse("2006-01-02", timeStr)
|
||||
return t.Unix() - TimeOffset
|
||||
}
|
||||
|
||||
//Get the timestamp at 12 o'clock on the day
|
||||
func GetCurDayHalfTimestamp() int64 {
|
||||
return GetCurDayZeroTimestamp() + HalfOffset
|
||||
|
||||
}
|
||||
|
||||
//Get the formatted time at 0 o'clock of the day, the format is "2006-01-02_00-00-00"
|
||||
func GetCurDayZeroTimeFormat() string {
|
||||
return time.Unix(GetCurDayZeroTimestamp(), 0).Format("2006-01-02_15-04-05")
|
||||
}
|
||||
|
||||
//Get the formatted time at 12 o'clock of the day, the format is "2006-01-02_12-00-00"
|
||||
func GetCurDayHalfTimeFormat() string {
|
||||
return time.Unix(GetCurDayZeroTimestamp()+HalfOffset, 0).Format("2006-01-02_15-04-05")
|
||||
}
|
||||
func GetTimeStampByFormat(datetime string) string {
|
||||
timeLayout := "2006-01-02 15:04:05" //转化所需模板
|
||||
loc, _ := time.LoadLocation("Local") //获取时区
|
||||
tmp, _ := time.ParseInLocation(timeLayout, datetime, loc)
|
||||
timestamp := tmp.Unix() //转化为时间戳 类型是int64
|
||||
return strconv.FormatInt(timestamp, 10)
|
||||
}
|
||||
|
||||
func TimeStringFormatTimeUnix(timeFormat string, timeSrc string) int64 {
|
||||
tm, _ := time.Parse(timeFormat, timeSrc)
|
||||
return tm.Unix()
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
|
||||
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
|
||||
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext"
|
||||
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
var (
|
||||
pkgLogger Logger
|
||||
sp = string(filepath.Separator)
|
||||
logLevelMap = map[int]zapcore.Level{
|
||||
6: zapcore.DebugLevel,
|
||||
5: zapcore.DebugLevel,
|
||||
4: zapcore.InfoLevel,
|
||||
3: zapcore.WarnLevel,
|
||||
2: zapcore.ErrorLevel,
|
||||
1: zapcore.FatalLevel,
|
||||
0: zapcore.PanicLevel,
|
||||
}
|
||||
)
|
||||
|
||||
// InitFromConfig initializes a Zap-based logger
|
||||
func InitFromConfig(loggerPrefixName, moduleName string, logLevel int, isStdout bool, isJson bool, logLocation string, rotateCount uint) error {
|
||||
l, err := NewZapLogger(loggerPrefixName, moduleName, logLevel, isStdout, isJson, logLocation, rotateCount)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pkgLogger = l.WithCallDepth(2)
|
||||
if isJson {
|
||||
pkgLogger = pkgLogger.WithName(moduleName)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ZDebug(ctx context.Context, msg string, keysAndValues ...interface{}) {
|
||||
if pkgLogger == nil {
|
||||
return
|
||||
}
|
||||
pkgLogger.Debug(ctx, msg, keysAndValues...)
|
||||
}
|
||||
|
||||
func ZInfo(ctx context.Context, msg string, keysAndValues ...interface{}) {
|
||||
if pkgLogger == nil {
|
||||
return
|
||||
}
|
||||
pkgLogger.Info(ctx, msg, keysAndValues...)
|
||||
}
|
||||
|
||||
func ZWarn(ctx context.Context, msg string, err error, keysAndValues ...interface{}) {
|
||||
if pkgLogger == nil {
|
||||
return
|
||||
}
|
||||
pkgLogger.Warn(ctx, msg, err, keysAndValues...)
|
||||
}
|
||||
|
||||
func ZError(ctx context.Context, msg string, err error, keysAndValues ...interface{}) {
|
||||
if pkgLogger == nil {
|
||||
return
|
||||
}
|
||||
pkgLogger.Error(ctx, msg, err, keysAndValues...)
|
||||
}
|
||||
|
||||
type ZapLogger struct {
|
||||
zap *zap.SugaredLogger
|
||||
level zapcore.Level
|
||||
loggerName string
|
||||
loggerPrefixName string
|
||||
}
|
||||
|
||||
func NewZapLogger(loggerPrefixName, loggerName string, logLevel int, isStdout bool, isJson bool, logLocation string, rotateCount uint) (*ZapLogger, error) {
|
||||
zapConfig := zap.Config{
|
||||
Level: zap.NewAtomicLevelAt(logLevelMap[logLevel]),
|
||||
// EncoderConfig: zap.NewProductionEncoderConfig(),
|
||||
// InitialFields: map[string]interface{}{"PID": os.Getegid()},
|
||||
DisableStacktrace: true,
|
||||
}
|
||||
if isJson {
|
||||
zapConfig.Encoding = "json"
|
||||
} else {
|
||||
zapConfig.Encoding = "console"
|
||||
}
|
||||
// if isStdout {
|
||||
// zapConfig.OutputPaths = append(zapConfig.OutputPaths, "stdout", "stderr")
|
||||
// }
|
||||
zl := &ZapLogger{level: logLevelMap[logLevel], loggerName: loggerName, loggerPrefixName: loggerPrefixName}
|
||||
opts, err := zl.cores(isStdout, isJson, logLocation, rotateCount)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l, err := zapConfig.Build(opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
zl.zap = l.Sugar()
|
||||
return zl, nil
|
||||
}
|
||||
|
||||
func (l *ZapLogger) cores(isStdout bool, isJson bool, logLocation string, rotateCount uint) (zap.Option, error) {
|
||||
c := zap.NewProductionEncoderConfig()
|
||||
c.EncodeTime = l.timeEncoder
|
||||
c.EncodeDuration = zapcore.SecondsDurationEncoder
|
||||
c.MessageKey = "msg"
|
||||
c.LevelKey = "level"
|
||||
c.TimeKey = "time"
|
||||
c.CallerKey = "caller"
|
||||
c.NameKey = "logger"
|
||||
var fileEncoder zapcore.Encoder
|
||||
if isJson {
|
||||
c.EncodeLevel = zapcore.CapitalLevelEncoder
|
||||
fileEncoder = zapcore.NewJSONEncoder(c)
|
||||
fileEncoder.AddInt("PID", os.Getpid())
|
||||
} else {
|
||||
c.EncodeLevel = l.capitalColorLevelEncoder
|
||||
c.EncodeCaller = l.customCallerEncoder
|
||||
fileEncoder = zapcore.NewConsoleEncoder(c)
|
||||
}
|
||||
writer, err := l.getWriter(logLocation, rotateCount)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var cores []zapcore.Core
|
||||
// if logLocation == "" && !isStdout {
|
||||
// return nil, errors.New("log storage location is empty and not stdout")
|
||||
// }
|
||||
if logLocation != "" {
|
||||
cores = []zapcore.Core{
|
||||
zapcore.NewCore(fileEncoder, writer, zap.NewAtomicLevelAt(l.level)),
|
||||
}
|
||||
}
|
||||
if isStdout {
|
||||
cores = append(cores, zapcore.NewCore(fileEncoder, zapcore.Lock(os.Stdout), zap.NewAtomicLevelAt(l.level)))
|
||||
// cores = append(cores, zapcore.NewCore(fileEncoder, zapcore.Lock(os.Stderr), zap.NewAtomicLevelAt(l.level)))
|
||||
}
|
||||
return zap.WrapCore(func(c zapcore.Core) zapcore.Core {
|
||||
return zapcore.NewTee(cores...)
|
||||
}), nil
|
||||
}
|
||||
|
||||
func (l *ZapLogger) customCallerEncoder(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
|
||||
s := "[" + caller.TrimmedPath() + "]"
|
||||
// color, ok := _levelToColor[l.level]
|
||||
// if !ok {
|
||||
// color = _levelToColor[zapcore.ErrorLevel]
|
||||
// }
|
||||
enc.AppendString(s)
|
||||
|
||||
}
|
||||
|
||||
func (l *ZapLogger) timeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
|
||||
layout := "2006-01-02 15:04:05.000"
|
||||
type appendTimeEncoder interface {
|
||||
AppendTimeLayout(time.Time, string)
|
||||
}
|
||||
if enc, ok := enc.(appendTimeEncoder); ok {
|
||||
enc.AppendTimeLayout(t, layout)
|
||||
return
|
||||
}
|
||||
enc.AppendString(t.Format(layout))
|
||||
}
|
||||
|
||||
func (l *ZapLogger) getWriter(logLocation string, rorateCount uint) (zapcore.WriteSyncer, error) {
|
||||
logf, err := rotatelogs.New(logLocation+sp+l.loggerPrefixName+".%Y-%m-%d",
|
||||
rotatelogs.WithRotationCount(rorateCount),
|
||||
rotatelogs.WithRotationTime(time.Duration(config.Config.Log.RotationTime)*time.Hour),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return zapcore.AddSync(logf), nil
|
||||
}
|
||||
|
||||
func (l *ZapLogger) capitalColorLevelEncoder(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
|
||||
s, ok := _levelToCapitalColorString[level]
|
||||
if !ok {
|
||||
s = _unknownLevelColor[zapcore.ErrorLevel]
|
||||
}
|
||||
pid := fmt.Sprintf("["+"PID:"+"%d"+"]", os.Getpid())
|
||||
color := _levelToColor[level]
|
||||
enc.AppendString(s)
|
||||
enc.AppendString(color.Add(pid))
|
||||
if l.loggerName != "" {
|
||||
enc.AppendString(color.Add(l.loggerName))
|
||||
}
|
||||
}
|
||||
|
||||
func (l *ZapLogger) ToZap() *zap.SugaredLogger {
|
||||
return l.zap
|
||||
}
|
||||
|
||||
func (l *ZapLogger) Debug(ctx context.Context, msg string, keysAndValues ...interface{}) {
|
||||
keysAndValues = l.kvAppend(ctx, keysAndValues)
|
||||
l.zap.Debugw(msg, keysAndValues...)
|
||||
}
|
||||
|
||||
func (l *ZapLogger) Info(ctx context.Context, msg string, keysAndValues ...interface{}) {
|
||||
keysAndValues = l.kvAppend(ctx, keysAndValues)
|
||||
l.zap.Infow(msg, keysAndValues...)
|
||||
}
|
||||
|
||||
func (l *ZapLogger) Warn(ctx context.Context, msg string, err error, keysAndValues ...interface{}) {
|
||||
if err != nil {
|
||||
keysAndValues = append(keysAndValues, "error", err.Error())
|
||||
}
|
||||
keysAndValues = l.kvAppend(ctx, keysAndValues)
|
||||
l.zap.Warnw(msg, keysAndValues...)
|
||||
}
|
||||
|
||||
func (l *ZapLogger) Error(ctx context.Context, msg string, err error, keysAndValues ...interface{}) {
|
||||
if err != nil {
|
||||
keysAndValues = append(keysAndValues, "error", err.Error())
|
||||
}
|
||||
keysAndValues = l.kvAppend(ctx, keysAndValues)
|
||||
l.zap.Errorw(msg, keysAndValues...)
|
||||
}
|
||||
|
||||
func (l *ZapLogger) kvAppend(ctx context.Context, keysAndValues []interface{}) []interface{} {
|
||||
if ctx == nil {
|
||||
return keysAndValues
|
||||
}
|
||||
operationID := mcontext.GetOperationID(ctx)
|
||||
opUserID := mcontext.GetOpUserID(ctx)
|
||||
connID := mcontext.GetConnID(ctx)
|
||||
triggerID := mcontext.GetTriggerID(ctx)
|
||||
opUserPlatform := mcontext.GetOpUserPlatform(ctx)
|
||||
remoteAddr := mcontext.GetRemoteAddr(ctx)
|
||||
if opUserID != "" {
|
||||
keysAndValues = append([]interface{}{constant.OpUserID, opUserID}, keysAndValues...)
|
||||
}
|
||||
if operationID != "" {
|
||||
keysAndValues = append([]interface{}{constant.OperationID, operationID}, keysAndValues...)
|
||||
}
|
||||
if connID != "" {
|
||||
keysAndValues = append([]interface{}{constant.ConnID, connID}, keysAndValues...)
|
||||
}
|
||||
if triggerID != "" {
|
||||
keysAndValues = append([]interface{}{constant.TriggerID, triggerID}, keysAndValues...)
|
||||
}
|
||||
if opUserPlatform != "" {
|
||||
keysAndValues = append([]interface{}{constant.OpUserPlatform, opUserPlatform}, keysAndValues...)
|
||||
}
|
||||
if remoteAddr != "" {
|
||||
keysAndValues = append([]interface{}{constant.RemoteAddr, remoteAddr}, keysAndValues...)
|
||||
}
|
||||
return keysAndValues
|
||||
}
|
||||
|
||||
func (l *ZapLogger) WithValues(keysAndValues ...interface{}) Logger {
|
||||
dup := *l
|
||||
dup.zap = l.zap.With(keysAndValues...)
|
||||
return &dup
|
||||
}
|
||||
|
||||
func (l *ZapLogger) WithName(name string) Logger {
|
||||
dup := *l
|
||||
dup.zap = l.zap.Named(name)
|
||||
return &dup
|
||||
}
|
||||
|
||||
func (l *ZapLogger) WithCallDepth(depth int) Logger {
|
||||
dup := *l
|
||||
dup.zap = l.zap.WithOptions(zap.AddCallerSkip(depth))
|
||||
return &dup
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type ZkLogger struct{}
|
||||
|
||||
func NewZkLogger() *ZkLogger {
|
||||
return &ZkLogger{}
|
||||
}
|
||||
|
||||
func (l *ZkLogger) Printf(format string, a ...interface{}) {
|
||||
ZInfo(context.Background(), "zookeeper output", "msg", fmt.Sprintf(format, a...))
|
||||
}
|
||||
Reference in New Issue
Block a user