golang 里 context 和 logger 绑定的问题

142 天前
 liudon
import (
	"context"

	"github.com/pingcap/log"
	"go.uber.org/zap"
	iris "github.com/kataras/iris/v12"
)

func NewContext(ctx iris.Context, fields ...zap.Field) iris.Context {
	ctx.Values().Set(loggerKey, WithContext(ctx).With(fields...))
	return ctx
}

func WithContext(ctx iris.Context) *zap.Logger {
	if ctx == nil {
		return log.L()
	}

	if ctxLogger, ok := ctx.Values().Get(loggerKey).(*zap.Logger); ok {
		return ctxLogger
	} else {
		return log.L()
	}
}

func NewStdContext(ctx context.Context, fields ...zap.Field) iris.Context {
	ctx.WithValue(ctx, loggerKey, WithStdContext(ctx).With(fields...))
	return ctx
}

func WithStdContext(ctx context.Context) *zap.Logger {
	if ctx == nil {
		return log.L()
	}

	if ctxLogger, ok := ctx.Value(loggerKey).(*zap.Logger); ok {
		return ctxLogger
	} else {
		return log.L()
	}
}

分别用到了 iris.Context 和 context.Context ,现在要给每个 context 写一个绑定方法。 请教下,有没有更好的实现方式?

1016 次点击
所在节点    Go 编程语言
3 条回复
gitrebase
142 天前
没用过 iris 、但用过 gin

在 gin 的设计里,gin.Context 中会包含 context.Context 字段,所以直接 set 到 context.Context 里就行,就不存在“要给每个 context 写一个绑定方法”
pennai
142 天前
把这两包一下,不就是一个了,不一定非得用原生的
bv
142 天前
不要啥都往 context.Context 里面塞,塞一次 ctx 就多包裹一层。

1. 可以自定义 iris 自带的 logger 。

func main() {
app := iris.New()
logger := app.Logger()
logger.Printer.Output = os.Stderr

app.Get("/hello", func(ctx *irisctx.Context) {
log := ctx.Application().Logger()
log.Info("HELLO")
})
}

2. 使用依赖注入

type DemoAPI struct {
log *zap.Logger
}

func (a DemoAPI) Hello(ctx *irisctx.Context) {
a.log.Info("HELLO")
}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1002087

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX