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

203 lines
5.9 KiB

2 years ago
package log
import (
"context"
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) error {
l, err := NewZapLogger(logLevel, isStdout, isJson)
2 years ago
if err != nil {
return err
2 years ago
}
pkgLogger = l.WithCallDepth(2).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 {
zap *zap.SugaredLogger
}
2 years ago
func NewZapLogger(logLevel int, isStdout bool, isJson bool) (*ZapLogger, error) {
2 years ago
zapConfig := zap.Config{
2 years ago
Level: zap.NewAtomicLevelAt(logLevelMap[logLevel]),
2 years ago
EncoderConfig: zap.NewProductionEncoderConfig(),
InitialFields: map[string]interface{}{"PID": os.Getegid()},
DisableStacktrace: true,
2 years ago
}
2 years ago
if isJson {
zapConfig.Encoding = "json"
}
if isStdout {
zapConfig.OutputPaths = append(zapConfig.OutputPaths, "stdout", "stderr")
2 years ago
}
zl := &ZapLogger{}
2 years ago
opts, err := zl.cores(logLevel, isStdout)
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(logLevel int, isStdout bool) (zap.Option, error) {
2 years ago
c := zap.NewProductionEncoderConfig()
2 years ago
c.EncodeTime = zapcore.ISO8601TimeEncoder
2 years ago
c.EncodeDuration = zapcore.SecondsDurationEncoder
c.EncodeLevel = zapcore.CapitalLevelEncoder
2 years ago
c.MessageKey = "msg"
c.LevelKey = "level"
c.TimeKey = "time"
c.CallerKey = "caller"
2 years ago
fileEncoder := zapcore.NewJSONEncoder(c)
2 years ago
fileEncoder.AddInt("PID", os.Getpid())
2 years ago
writer, err := l.getWriter()
if err != nil {
return nil, err
}
2 years ago
var cores []zapcore.Core
if config.Config.Log.StorageLocation != "" {
cores = []zapcore.Core{
2 years ago
zapcore.NewCore(fileEncoder, writer, zap.NewAtomicLevelAt(zapcore.Level(logLevel))),
2 years ago
}
2 years ago
}
2 years ago
if isStdout {
cores = append(cores, zapcore.NewCore(fileEncoder, zapcore.Lock(os.Stdout), zap.NewAtomicLevelAt(zapcore.Level(logLevel))))
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) getWriter() (zapcore.WriteSyncer, error) {
logf, err := rotatelogs.New(config.Config.Log.StorageLocation+sp+"OpenIM.log.all"+".%Y-%m-%d",
rotatelogs.WithRotationCount(config.Config.Log.RemainRotationCount),
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
}
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
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
}