initializing has been changed.

This commit is contained in:
crusader 2017-09-11 12:42:00 +09:00
parent 0d223d2580
commit 25aa9161b8
2 changed files with 26 additions and 24 deletions

View File

@ -2,3 +2,4 @@ package: git.loafle.net/commons_go/logging
import: import:
- package: go.uber.org/zap - package: go.uber.org/zap
version: v1.5.0 version: v1.5.0
- package: git.loafle.net/commons_go/config

View File

@ -1,41 +1,42 @@
package logging package logging
import ( import (
"context" "encoding/json"
"os"
"path" "git.loafle.net/commons_go/config"
"go.uber.org/zap" "go.uber.org/zap"
"go.uber.org/zap/zapcore"
) )
type loggerKeyType int type loggerKeyType int
const loggerKey loggerKeyType = iota const loggerKey loggerKeyType = iota
var defaultLogger *zap.Logger var Logger *zap.Logger
func init() { func init() {
l, _ := zap.NewDevelopment() conf := config.New()
defaultLogger = l.With( conf.SetConfigName("logging")
zap.Int("pid", os.Getpid()), conf.SetConfigType("json")
zap.String("exe", path.Base(os.Args[0])), 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 { buf, err := conf.Marshal("json")
if nil != logger { if err != nil {
return context.WithValue(ctx, loggerKey, logger.With(fields...)) panic(err)
} }
return context.WithValue(ctx, loggerKey, WithContext(ctx).With(fields...)) var cfg zap.Config
if err = json.Unmarshal(buf, &cfg); err != nil {
panic(err)
} }
func WithContext(ctx context.Context) *zap.Logger { Logger, err = cfg.Build()
if ctx == nil { if err != nil {
return defaultLogger panic(err)
} }
if ctxLogger, ok := ctx.Value(loggerKey).(*zap.Logger); ok {
return ctxLogger
}
return defaultLogger
} }