V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
liudon
V2EX  ›  Go 编程语言

golang 里 context 和 logger 绑定的问题

  •  
  •   liudon · 129 天前 · 1002 次点击
    这是一个创建于 129 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 写一个绑定方法。 请教下,有没有更好的实现方式?

    3 条回复    2023-12-21 10:26:10 +08:00
    gitrebase
        1
    gitrebase  
       129 天前
    没用过 iris 、但用过 gin

    在 gin 的设计里,gin.Context 中会包含 context.Context 字段,所以直接 set 到 context.Context 里就行,就不存在“要给每个 context 写一个绑定方法”
    pennai
        2
    pennai  
       129 天前
    把这两包一下,不就是一个了,不一定非得用原生的
    bv
        3
    bv  
       128 天前
    不要啥都往 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")
    }
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1038 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 156ms · UTC 23:02 · PVG 07:02 · LAX 16:02 · JFK 19:02
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.