Skip to content

Logging with trace ID from header #2348

Discussion options

You must be logged in to vote

I resolve problem by custom zap logger with "With" function as parent logger and attach to echo.Context

`func NewContext(ctx echo.Context, fields ...zapcore.Field) echo.Context {
	ctx.Set(loggerKey, WithContext(ctx).With(fields...))
	return ctx
}
func WithContext(ctx echo.Context) *zap.Logger {
	if ctx == nil {
		return Logx
	}
	if ctxLogger, ok := ctx.Get(loggerKey).(*zap.Logger); ok {
		return ctxLogger
	}
	return Logx
}

func createContext(c echo.Context) echo.Context {
	return util.NewContext(c, zap.String("reqID", "xxxxx"))
}

`
when need add key, I use

`rqCtx := createContext(c)
Info(rqCtx)

func Info(ctx echo.Context, msg string, fields ...zapcore.Field) {
	ctx.Get(loggerKey).(*zap…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by vuhoanghiep1993
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants