diff --git a/glide.yaml b/glide.yaml index b968be4..a8c23f1 100644 --- a/glide.yaml +++ b/glide.yaml @@ -1,4 +1,5 @@ package: git.loafle.net/commons_go/logging import: - package: go.uber.org/zap - version: v1.5.0 \ No newline at end of file + version: v1.5.0 +- package: git.loafle.net/commons_go/config diff --git a/logging.go b/logging.go index 20ae409..e1834d0 100644 --- a/logging.go +++ b/logging.go @@ -1,41 +1,42 @@ package logging import ( - "context" - "os" - "path" + "encoding/json" + + "git.loafle.net/commons_go/config" "go.uber.org/zap" - "go.uber.org/zap/zapcore" ) type loggerKeyType int const loggerKey loggerKeyType = iota -var defaultLogger *zap.Logger +var Logger *zap.Logger func init() { - l, _ := zap.NewDevelopment() - defaultLogger = l.With( - zap.Int("pid", os.Getpid()), - zap.String("exe", path.Base(os.Args[0])), - ) -} + conf := config.New() + conf.SetConfigName("logging") + conf.SetConfigType("json") + conf.AddConfigPath(".") + conf.AddConfigPath("./config") + err := conf.ReadInConfig() + if nil != err { + panic(err) + } -func NewContext(ctx context.Context, logger *zap.Logger, fields ...zapcore.Field) context.Context { - if nil != logger { - return context.WithValue(ctx, loggerKey, logger.With(fields...)) + buf, err := conf.Marshal("json") + if err != nil { + panic(err) + } + var cfg zap.Config + if err = json.Unmarshal(buf, &cfg); err != nil { + panic(err) } - return context.WithValue(ctx, loggerKey, WithContext(ctx).With(fields...)) -} -func WithContext(ctx context.Context) *zap.Logger { - if ctx == nil { - return defaultLogger + Logger, err = cfg.Build() + if err != nil { + panic(err) } - if ctxLogger, ok := ctx.Value(loggerKey).(*zap.Logger); ok { - return ctxLogger - } - return defaultLogger + }