Since pylogix does not raise exceptions for communication or tag errors, you must manually check the .Status attribute of the returned object. To implement robust logging, use the datetime library to timestamp errors and write them to a file.
When writing to a log file, call log.flush() immediately after writing an error to ensure the entry is saved to disk in the event of an application crash. Always ensure you call log.close() at the end of your application lifecycle to release the file handle.
import datetime
now = datetime.datetime.now()
log = open("log.txt", "a+")
# Example operation
ret = Read(plc_tag)
if ret.Status == "Success":
# Handle successful read
tags_list.append(ret.TagName + "|" + str(ret.Value))
else:
# Log the error with timestamp and status
log.write("%s Save Error: %s tag %s\n" % (now.strftime("%c"), ret.TagName, ret.Status))
log.flush() # Ensures log is written even if the app crashes
# At the end of the application
log.close()