Tags: Debugging (1)


Logging In Python Dynamo Node

19 July 2017 - 08:11 pm
Python,Revit,Dynamo
Let's talk logging in dynamo.

Earlier, I realized earlier on that debugging is difficult if you aren't logging your output. Unlike ghPython in grasshopper, python in dynamo doesn't currently natively have a console to "print" to. So to handle this I have a log and clearLog() function I always tend to use. This writes to a text file path that you will see in the code.



My Typical Log for dynamo


# <------------ LOG DYNAMO STUFF -------------------->#
import time,datetime

#<----- EDIT BELOW --->

#constants
LOGFILE = "C:\Path\To\A\log.txt" #path to save text
LOG_ACTIVE = True #Setting to False will disable the log

# <---- END EDIT ---->

def log(textArr,is_raw=False):
global LOGFILE,LOG_ACTIVE
if LOG_ACTIVE:
activeScript = ""
#---- prefix to identify time and script running ---#
ts = time.time()
timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
precursor ="[" timestamp "] --> "
#---- end prefix --->
filename = LOGFILE
if not isinstance(textArr, (list, tuple)):
textArr = [textArr]
target = open(filename, 'a ')
target.write("\n")
target.write(precursor)
for i in textArr:
if (not is_raw):
target.write(repr(i))
else:
target.write(i)
target.close()

def clearLog():
global LOGFILE,LOG_ACTIVE
if LOG_ACTIVE:
filename = LOGFILE
target = open(filename, 'w ')
target.write("")
target.close()

# <------------ LOG DYNAMO STUFF -------------------->#


Log Example


Now you can call these two functions like so. Each log call, will print a single line of text

#clear the log. usually I run this at the beginning of my script.
clearLog()
#simple single values
log("hello world")
#multiple concatenated values via a list or tuple (will automatically give text version)
foo = 5
log(["hello the value of foo is: ",foo, "!!!"])

I then usually open it in a browser to easily refresh the value of the log.txt file. Boom, your own external console.

Disabling the Log


After debugging your scripts, you'll obviously want to disable logging features. To Disable the log, change the LOG_ACTIVE value to False. This will not write to any file when the log functions are called, without you having to delete or comment them out.

LOG_ACTIVE = False #Setting to False will disable the log
Chris Malcolm

Chris Malcolm is an aspiring architect, web developer, and designer originally from Florida. A MIT M.Arch Graduate, he currently is based in San Francisco, employed by Skidmore Owings and Merrill. He enjoys creating tools both professionally and for fun. As for tooling, architecturally speaking, Rhino and Grasshopper is his first love, with revit,dynamo,passion as close seconds. Outside of architecture tooling, he loves all things javascript, html, python, and regular expressions.

More projects and info at my main site:
Chris-malcolm.com