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:
- package: go.uber.org/zap
version: v1.5.0
- package: git.loafle.net/commons_go/config

View File

@ -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
}