Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🤗 [Question]: Is there any way to log request id on handler? #3169

Closed
3 tasks done
gunb0s opened this issue Oct 15, 2024 · 10 comments
Closed
3 tasks done

🤗 [Question]: Is there any way to log request id on handler? #3169

gunb0s opened this issue Oct 15, 2024 · 10 comments

Comments

@gunb0s
Copy link

gunb0s commented Oct 15, 2024

Question Description

i'm new to go fiber and develop with uber zap, fx.
The problem is i know how to log request id in middleware logger, But I made a another logger to use on handler and using it by dependency injection.
how can i log request id on second logger?

i guess that i can make a log function to accept fiber context as parameter, and extract request id from it,
but I wish there were other options than this, like in middleware, which can be pre-set

Code Snippet (optional)

var Module = fx.Module(
	"external",
	fx.Provide(
		database.NewPostgres,
		logger.New,
	),
)

type External struct {
	fx.In

	Logger *logger.Sugared
	DB     *gorm.DB
}

type productService struct {
	ex external.External
}

func (s productService) GetAllProducts(c dto.GetAllProductParam) ([]model.Product, int, error) {
	var products []model.Product
	var count int64
	limit, offset := c.Limit, c.Offset
	queryResult := s.ex.DB.Scopes(database.Paginate(limit, offset)).Find(&products)
	queryResult = s.ex.DB.Model(&model.Product{}).Count(&count)
	
	s.ex.Logger.Printf("request Id needed")

	return products, int(count), queryResult.Error
}

Checklist:

  • I agree to follow Fiber's Code of Conduct.
  • I have checked for existing issues that describe my questions prior to opening this one.
  • I understand that improperly formatted questions may be closed without explanation.
Copy link

welcome bot commented Oct 15, 2024

Thanks for opening your first issue here! 🎉 Be sure to follow the issue template! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

@gunb0s gunb0s changed the title 🤗 [Question]: Is there any to log request id on handler? 🤗 [Question]: Is there any way to log request id on handler? Oct 15, 2024
@ReneWerner87
Copy link
Member

@gunb0s
Copy link
Author

gunb0s commented Oct 15, 2024

you can use the https://docs.gofiber.io/contrib/fiberzap_v2.x.x/fiberzap/ for this

https://github.com/gofiber/contrib/blob/main/fiberzap/zap.go#L168

this way needs fiber context at every situation.. right?

@ReneWerner87
Copy link
Member

yes as middleware it works directly with the fiber context

https://github.com/gofiber/contrib/blob/f4145f79af4e39b26515340bf92c879ccc350b4f/fiberzap/zap_test.go#L290-L308

the question is whether you need a req/res logger or just want to log additional information

the variant I have shown you is an independent middleware for logging the req/res data

@gunb0s
Copy link
Author

gunb0s commented Oct 15, 2024

yes as middleware it works directly with the fiber context

https://github.com/gofiber/contrib/blob/f4145f79af4e39b26515340bf92c879ccc350b4f/fiberzap/zap_test.go#L290-L308

the question is whether you need a req/res logger or just want to log additional information

the variant I have shown you is an independent middleware for logging the req/res data

my question is about that i want to log additional information, not in req/res logger
like trace id, in opentelemetry

@ReneWerner87
Copy link
Member

ok, how do you generate this requestID ? with the middleware?
https://docs.gofiber.io/api/middleware/requestid

@ReneWerner87
Copy link
Member

ReneWerner87 commented Oct 15, 2024

you can always inject a middleware that logs this id or does other things

	app.Use(func(c *fiber.Ctx) error {
        // log requestId
        log.Println("requestId:", c.Locals("requestid")) // requestId from the locals(context) object - https://docs.gofiber.io/api/middleware/requestid#config
        log.Println("requestId:", c.Get(fiber.HeaderXRequestID)) // requestId from the request header
        return c.Next()
    })

@gunb0s
Copy link
Author

gunb0s commented Oct 15, 2024

Instead of using middleware, if I want to log additional information in an API controller or service, do I always need the Fiber context to get the request ID? If that's the case, it feels inconvenient to pass the context to the logger each time like this:

sugarLogger.With(
	zap.String("requestID", context.Get(fiber.HeaderXRequestID)),
).Infof("Printf-style logging with context: %s", "additional info")

I'm looking for a different approach because it seems cumbersome to log this way. The reason I want to implement this is to distinguish logs from the same request when multiple requests come in simultaneously.

@ReneWerner87
Copy link
Member

ReneWerner87 commented Oct 15, 2024

all request and response information can be found in the fiber context
in order to access this information, it is necessary to use it
you can also extract this information and pass it on later or add it beforehand

app.Use(func(c *fiber.Ctx) error {
		// extend and (TODO) store this logger
		zap.With(zap.String("requestId", c.Get(fiber.HeaderXRequestID)).Info("requestId"))
		return c.Next()
})

@gunb0s
Copy link
Author

gunb0s commented Oct 15, 2024

I think this way is best for my situation, I'll try it thank you!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants