Logging to Zope error_log in product or TTW code
Note: this article is written for Zope 2.7. I think the error_log api is very stable, however this is certainly subject to change for future versions of Zope.
Note: there is also a short recipe for this on zope labs: http://zopelabs.com/cookbook/1055543667.
There are times, rare though they may be, when in your own product code, you want to log to the zope error log and continue processing. In one use case, I wanted to log an error and email myself when an exception was raised, but continue processing as if nothing had happened. This may seem like shoddy design, but I needed this in particular to help diagnose an error that occurred only rarely.
You can't to this from TTW code because the function used to log to the error_log is protected. So, if you need to do this from TTW code (as I did), you can use an external method. Otherwise, just place the following snippet or a modification thereof, in an appropriate place in your product code.
import sys
def log_traceback(context):
error_log = context.error_log
url = error_log.raising( sys.exc_info() )
#url is in format:
#path_to_error_log?id=error_id
text = url
if url.find('id=')>-1:
eid = url[url.find('id=')+3:]
text = error_log.getLogEntryById(eid)
return (text,url)
The api function in the error log you need to call is error_log.raising(), which takes as a parameter the tuple returned from sys.exc_info(). raising() returns the absolute url to the error just logged.
This function returns a tuple containing the log entry of the error and the url to the error. Of course, you can use this return data however you want. In the example I cited above, it was emailed to me. You can get the text version of the log entry by str(log_entry).
Another interesting use case for this, and the main reason for writing this article, is Silva Code Sources. As of Silva 1.4.1, if you are developing a code source and it has an error in it, you only see the error that was raised, like AttributeError: variable. It can be VERY difficult to troubleshoot this, as you have no access to REQUEST, or to the traceback. I think that Silva Code Sources should log to the error log when the code source fails, but still return a graceful error like they currently do.