Spot any errors? let me know, but Unleash your pedant politely please.

Monday 1 June 2009

Determine current stack depth

If anyone knows of a better way to do this, do let me know...

The test harness I'm writing produces a lot of logging information. It's necessary to record what test are doing, where they fail etc, so that we can investigate and not just produce yet more useless metrics. One of the things I found myself doing was adding indentation so that the test cases, sub tests and test steps etc were shown with increasing indentation. As with source code, it makes the scope of the test results easier to follow.

The more I was adding this by hand, the more I though that maybe there was a better way to do things. I'm probably going to so something a little more intelligent, but for now I've gone with indenting my logs according to the call depth of the function that writes the log string.

At a fairly high level, there is a routine to print to the console and to a log file. References to this cascade through the code, so that this one function is the one that actually gets called when logging :

def printAndLog(self, logText):
print logText
self.log(logText)


All I need to do is determine the stack depth:
def callDepth():
depth = 0
while True:
try:
sys._getframe(depth)
depth +=1
except:
return depth - 1

and use it to add indentation...
def printAndLog(self, logText):
logText = ' ' * self.callDepth() + logText
print logText
self.log(logText)

Not sure that it's entirely legit to be calling _getframe, but it's working at the moment, and I'm not doing anything with the returned frames anyway.

No comments:

Post a Comment