0

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.

Raju Yadav
  • 57
  • 3

1 Answers1

0

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.

Yuri Chandra
  • 1
  • 1
  • 2
  • In case, if there no way then what about hexagonal architecture. Can we then conclude hexagonal architecture not possible in case we set something to Context and want to use detail set in context latter in the request flow ? In this case I would require to pass the context to domain functions and to the repository. What about clean code approach ? If at domain --> func GetProductById(ctx context.Context, id string) []Products { //Processing log.Info(ctx) repo.GetProductById(ctx, id ) } then again at repository layer func GetProductById(ctx context.Context, id string) []Products { } – Raju Yadav Sep 22 '22 at 13:32
  • Of course it's still possible to use both hexagonal architecture and context, using context won't violate any rules from hexagonal architecture. There are no correlation between hexagonal architecture and context for request flow. Hexagonal architecture is about how you group functionality into layers so those layers has clear separation of concern. Meanwhile using context allow you to "pass" data between layers. Yes, your example is correct. – Yuri Chandra Sep 22 '22 at 16:30
  • Passing the context between the layers will make them coupled together and it will not more remain clean code. Mixing the business parameter with infrastacture object(context) throughout the functional call across the layers is bad idea – Raju Yadav Jan 30 '23 at 08:20