Golang with hexagonal architecture with logging middleware. I dont want to pass context to each components and methods

Viewed 30

I am developing an application in golang with hexagonal architecture. I required to print the requestId in the logs where ever I want to use logs.

To do this, I am generating a random request Id and attaching it with the GIN context. And suppose I want to log info at repository adapter. My problem is that, in this case to be able to log I need to pass the context object to each and every components(layers) and each methods where I want to log request Id. This will be not according to hexagonal architecture and clean code. So, I dont want to pass context to each components and methods to be able to get the information set in GIN Context Is there a way like we do in spring, we can get the principle object anywhere once it get set in spring security context.

1 Answers

As far as I know, there are no such way except explicitly passing context object via function to layers/components afterwards. For the example:

func GetProducts(ctx context.Context) []Products

But what you can adjust is instead of using GIN context which heavily related to delivery/handler layer, you can utilize Golang native context package to distribute context to layers afterward.

Related