For each http request that my server receives I create a context by adding as value the pointer of a struct:
type BaseKey string
type Tracker struct{
Log []string
}
[...]
ctx := context.WithValue(r.Context(), BaseKey("someUniqueKey"), *Tracker{})
r = r.WithContext(ctx)
// (Actually I use http.Server.BaseContext but
// let's put it like this for simplicity's sake)
Then every time I run a function it reads the context and gets the Tracker
struct then writes in it the action to execute inside the Tracker.Log
slice, that is, in the whole tree of calls needed to fulfill the request a useful string is added for debugging, when there is an error the whole Tracker.Log
slice is joined and concatenated with the error and saved locally in the server log.
This sounds great but I was thinking, doesn’t this consume a lot of memory per request? Suppose I have 1000 requests and they all work and if so the Tracker.Log
slice would be totally ignored as it is only needed when there is an error, then this translates into useless memory consumption.
Should I be concerned about the amount of memory to be used in the Tracker.Log
slice? What other alternative do I have to achieve this?
An option that occurred to me (but honestly I see complicated to implement it), is that the Tracker.Log
slice should only be written when there is an error, that is to say we would go from bottom to top and when we arrive to the starting point we would register the error.
If I did not explain well imagine this tree:
-origin
-somefunction
-anotherfunction
-childfunction
If childfunction
fails it will log the error in the Tracker.Log
slice, then anotherfunction
will know that there was an error so it will log in the slice what it was trying to do, and again it will return an error to somefunction
and it will repeat the process, and so on until we get to origin
where we finally close the connection and log the error in the server, this way the slice would only be filled when there is an error.
Which of the two methods is more common?, in fact is even valid the first option how I am originally doing it?, do you think that the memory consumption of the first option is not very serious?