You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Open-IM-Server/pkg/common/log/zap.go

259 lines
7.5 KiB

2 years ago
package log
import (
"context"
2 years ago
"errors"
2 years ago
"fmt"
2 years ago
"os"
"path/filepath"
"time"
2 years ago
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
2 years ago
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext"
2 years ago
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
2 years ago
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var (
2 years ago
pkgLogger Logger = &ZapLogger{}
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,
}
2 years ago
)
// InitFromConfig initializes a Zap-based logger
2 years ago
func InitFromConfig(name string, logLevel int, isStdout bool, isJson bool, logLocation string, rotateCount uint) error {
2 years ago
l, err := NewZapLogger(name, logLevel, isStdout, isJson, logLocation, rotateCount)
2 years ago
if err != nil {
return err
2 years ago
}
2 years ago
pkgLogger = l.WithCallDepth(2)
if isJson {
pkgLogger = pkgLogger.WithName(name)
}
2 years ago
return nil
2 years ago
}
2 years ago
func ZDebug(ctx context.Context, msg string, keysAndValues ...interface{}) {
2 years ago
pkgLogger.Debug(ctx, msg, keysAndValues...)
}
2 years ago
func ZInfo(ctx context.Context, msg string, keysAndValues ...interface{}) {
2 years ago
pkgLogger.Info(ctx, msg, keysAndValues...)
}
2 years ago
func ZWarn(ctx context.Context, msg string, err error, keysAndValues ...interface{}) {
2 years ago
pkgLogger.Warn(ctx, msg, err, keysAndValues...)
}
2 years ago
func ZError(ctx context.Context, msg string, err error, keysAndValues ...interface{}) {
2 years ago
pkgLogger.Error(ctx, msg, err, keysAndValues...)
}
type ZapLogger struct {
2 years ago
zap *zap.SugaredLogger
level zapcore.Level
loggerName string
2 years ago
}
2 years ago
func NewZapLogger(loggerName string, logLevel int, isStdout bool, isJson bool, logLocation string, rotateCount uint) (*ZapLogger, error) {
2 years ago
zapConfig := zap.Config{
2 years ago
Level: zap.NewAtomicLevelAt(logLevelMap[logLevel]),
// EncoderConfig: zap.NewProductionEncoderConfig(),
2 years ago
// InitialFields: map[string]interface{}{"PID": os.Getegid()},
DisableStacktrace: true,
2 years ago
}
2 years ago
if isJson {
zapConfig.Encoding = "json"
} else {
zapConfig.Encoding = "console"
}
2 years ago
// if isStdout {
// zapConfig.OutputPaths = append(zapConfig.OutputPaths, "stdout", "stderr")
// }
2 years ago
zl := &ZapLogger{level: logLevelMap[logLevel], loggerName: loggerName}
2 years ago
opts, err := zl.cores(isStdout, isJson, logLocation, rotateCount)
2 years ago
if err != nil {
return nil, err
}
l, err := zapConfig.Build(opts)
2 years ago
if err != nil {
return nil, err
}
2 years ago
zl.zap = l.Sugar()
return zl, nil
}
2 years ago
func (l *ZapLogger) cores(isStdout bool, isJson bool, logLocation string, rotateCount uint) (zap.Option, error) {
2 years ago
c := zap.NewDevelopmentEncoderConfig()
2 years ago
c.EncodeTime = l.timeEncoder
2 years ago
c.EncodeDuration = zapcore.SecondsDurationEncoder
2 years ago
c.MessageKey = "msg"
c.LevelKey = "level"
c.TimeKey = "time"
2 years ago
c.CallerKey = "caller"
2 years ago
2 years ago
var fileEncoder zapcore.Encoder
if isJson {
2 years ago
c.EncodeLevel = zapcore.CapitalLevelEncoder
2 years ago
fileEncoder = zapcore.NewJSONEncoder(c)
2 years ago
fileEncoder.AddInt("PID", os.Getpid())
2 years ago
} else {
2 years ago
c.EncodeLevel = l.capitalColorLevelEncoder
c.EncodeCaller = l.customCallerEncoder
2 years ago
fileEncoder = zapcore.NewConsoleEncoder(c)
2 years ago
}
2 years ago
writer, err := l.getWriter(logLocation, rotateCount)
2 years ago
if err != nil {
return nil, err
}
2 years ago
var cores []zapcore.Core
2 years ago
if logLocation != "" && !isStdout {
2 years ago
cores = []zapcore.Core{
2 years ago
zapcore.NewCore(fileEncoder, writer, zap.NewAtomicLevelAt(l.level)),
2 years ago
}
2 years ago
}
2 years ago
if logLocation == "" && !isStdout {
2 years ago
return nil, errors.New("log storage location is empty and not stdout")
}
2 years ago
if isStdout {
2 years ago
cores = append(cores, zapcore.NewCore(fileEncoder, zapcore.Lock(os.Stdout), zap.NewAtomicLevelAt(l.level)))
2 years ago
}
2 years ago
return zap.WrapCore(func(c zapcore.Core) zapcore.Core {
return zapcore.NewTee(cores...)
2 years ago
}), nil
2 years ago
}
2 years ago
2 years ago
func (l *ZapLogger) customCallerEncoder(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
s := "[" + caller.TrimmedPath() + "]"
2 years ago
// color, ok := _levelToColor[l.level]
// if !ok {
// color = _levelToColor[zapcore.ErrorLevel]
// }
enc.AppendString(s)
2 years ago
}
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))
}
2 years ago
func (l *ZapLogger) getWriter(logLocation string, rorateCount uint) (zapcore.WriteSyncer, error) {
logf, err := rotatelogs.New(logLocation+sp+"OpenIM.log.all"+".%Y-%m-%d",
rotatelogs.WithRotationCount(rorateCount),
2 years ago
rotatelogs.WithRotationTime(time.Duration(config.Config.Log.RotationTime)*time.Hour),
2 years ago
)
2 years ago
if err != nil {
return nil, err
}
return zapcore.AddSync(logf), nil
2 years ago
}
2 years ago
func (l *ZapLogger) capitalColorLevelEncoder(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
2 years ago
s, ok := _levelToCapitalColorString[level]
2 years ago
if !ok {
2 years ago
s = _unknownLevelColor[zapcore.ErrorLevel]
2 years ago
}
2 years ago
pid := fmt.Sprintf("["+"PID:"+"%d"+"]", os.Getpid())
color := _levelToColor[level]
2 years ago
enc.AppendString(s)
2 years ago
enc.AppendString(color.Add(pid))
2 years ago
if l.loggerName != "" {
enc.AppendString(color.Add(l.loggerName))
}
2 years ago
}
2 years ago
func (l *ZapLogger) ToZap() *zap.SugaredLogger {
return l.zap
}
func (l *ZapLogger) Debug(ctx context.Context, msg string, keysAndValues ...interface{}) {
2 years ago
keysAndValues = l.kvAppend(ctx, keysAndValues)
2 years ago
l.zap.Debugw(msg, keysAndValues...)
}
func (l *ZapLogger) Info(ctx context.Context, msg string, keysAndValues ...interface{}) {
2 years ago
keysAndValues = l.kvAppend(ctx, keysAndValues)
2 years ago
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())
2 years ago
}
2 years ago
keysAndValues = l.kvAppend(ctx, keysAndValues)
2 years ago
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())
2 years ago
}
2 years ago
keysAndValues = append([]interface{}{constant.OperationID, mcontext.GetOperationID(ctx)}, keysAndValues...)
2 years ago
l.zap.Errorw(msg, keysAndValues...)
}
2 years ago
func (l *ZapLogger) kvAppend(ctx context.Context, keysAndValues []interface{}) []interface{} {
2 years ago
operationID := mcontext.GetOperationID(ctx)
opUserID := mcontext.GetOpUserID(ctx)
connID := mcontext.GetConnID(ctx)
2 years ago
triggerID := mcontext.GetTriggerID(ctx)
2 years ago
opUserPlatform := mcontext.GetOpUserPlatform(ctx)
remoteAddr := mcontext.GetRemoteAddr(ctx)
2 years ago
if opUserID != "" {
2 years ago
keysAndValues = append([]interface{}{constant.OpUserID, opUserID}, keysAndValues...)
2 years ago
}
if operationID != "" {
2 years ago
keysAndValues = append([]interface{}{constant.OperationID, operationID}, keysAndValues...)
2 years ago
}
2 years ago
if connID != "" {
2 years ago
keysAndValues = append([]interface{}{constant.ConnID, connID}, keysAndValues...)
}
if triggerID != "" {
keysAndValues = append([]interface{}{constant.TriggerID, triggerID}, keysAndValues...)
2 years ago
}
2 years ago
if opUserPlatform != "" {
keysAndValues = append([]interface{}{constant.OpUserPlatform, opUserPlatform}, keysAndValues...)
}
if remoteAddr != "" {
keysAndValues = append([]interface{}{constant.RemoteAddr, remoteAddr}, keysAndValues...)
}
2 years ago
return keysAndValues
}
2 years ago
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
2 years ago
dup.zap = l.zap.Named(name)
2 years ago
return &dup
}
func (l *ZapLogger) WithCallDepth(depth int) Logger {
dup := *l
dup.zap = l.zap.WithOptions(zap.AddCallerSkip(depth))
return &dup
}