A small nick: the code would be easier to read if the function returned immediately when debug is not enabled. That way the reader can immediately forget about that branch and focus on the case when debug is enabled. With the current version, the reader has to read ~20 lines of code to find the end of the if block to understand what is the second branch doing and either skip there & back or risk forgetting what was the second branch about by the time the end of if-block is reached.

Another benefit of my proposal is a lower level of indentation.

Consider this as a suggestion for future changes that you can ignore if you disagree with my reasoning.