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

176 lines
4.8 KiB

2 years ago
package log
import (
2 years ago
"OpenIM/pkg/common/config"
2 years ago
"OpenIM/pkg/common/constant"
"OpenIM/pkg/common/tracelog"
"context"
2 years ago
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
2 years ago
"os"
2 years ago
"path/filepath"
2 years ago
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var (
2 years ago
pkgLogger Logger = &ZapLogger{}
2 years ago
sp = string(filepath.Separator)
2 years ago
)
// InitFromConfig initializes a Zap-based logger
2 years ago
func InitFromConfig(name string) error {
2 years ago
l, err := NewZapLogger()
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
// store original logger without sampling to avoid multiple samplers
SampleDuration time.Duration
SampleInitial int
SampleInterval int
}
2 years ago
func NewZapLogger() (*ZapLogger, error) {
2 years ago
zapConfig := zap.Config{
2 years ago
Level: zap.NewAtomicLevelAt(zapcore.DebugLevel),
Development: true,
Encoding: "json",
EncoderConfig: zap.NewProductionEncoderConfig(),
2 years ago
//InitialFields: map[string]interface{}{"PID": os.Getegid()},
2 years ago
}
zl := &ZapLogger{}
if config.Config.Log.Stderr {
zapConfig.OutputPaths = append(zapConfig.OutputPaths, "stderr")
2 years ago
}
2 years ago
opts, err := zl.cores()
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) timeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
2 years ago
enc.AppendString(t.Format("2006-01-02 15:04:05"))
}
2 years ago
func (l *ZapLogger) cores() (zap.Option, error) {
2 years ago
c := zap.NewProductionEncoderConfig()
2 years ago
c.EncodeTime = zapcore.ISO8601TimeEncoder
2 years ago
c.EncodeDuration = zapcore.SecondsDurationEncoder
2 years ago
//c.EncodeLevel = zapcore.LowercaseColorLevelEncoder
2 years ago
fileEncoder := zapcore.NewJSONEncoder(c)
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{
zapcore.NewCore(fileEncoder, writer, zapcore.DebugLevel),
}
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)
}
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)
}
keysAndValues = append([]interface{}{constant.OperationID, tracelog.GetOperationID(ctx)}, keysAndValues...)
l.zap.Errorw(msg, keysAndValues...)
}
2 years ago
func (l *ZapLogger) kvAppend(ctx context.Context, keysAndValues []interface{}) []interface{} {
2 years ago
operationID := tracelog.GetOperationID(ctx)
opUserID := tracelog.GetOpUserID(ctx)
if opUserID != "" {
keysAndValues = append([]interface{}{constant.OpUserID, tracelog.GetOpUserID(ctx)}, keysAndValues...)
}
if operationID != "" {
keysAndValues = append([]interface{}{constant.OperationID, tracelog.GetOperationID(ctx)}, 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
}