V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
liudon

golang 里 context 和 logger 绑定的问题

  •  
  •   liudon · Dec 20, 2023 · 1738 views
    This topic created in 864 days ago, the information mentioned may be changed or developed.
    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 replies    2023-12-21 10:26:10 +08:00
    gitrebase
        1
    gitrebase  
       Dec 20, 2023
    没用过 iris 、但用过 gin

    在 gin 的设计里,gin.Context 中会包含 context.Context 字段,所以直接 set 到 context.Context 里就行,就不存在“要给每个 context 写一个绑定方法”
    pennai
        2
    pennai  
       Dec 20, 2023
    把这两包一下,不就是一个了,不一定非得用原生的
    bv
        3
    bv  
       Dec 21, 2023
    不要啥都往 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")
    }
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2343 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 04:41 · PVG 12:41 · LAX 21:41 · JFK 00:41
    ♥ Do have faith in what you're doing.