[Python-ideas] Adding exception logging function to syslog module.

Eric Smith eric at trueblade.com
Tue Mar 23 00:31:08 CET 2010

Sean Reifschneider wrote:
> As someone who writes mostly programs that run unattended on servers, one
> thing I often want to do is have my tracebacks logged to syslog.  I would
> propose adding something like the following to the syslog module:
>    def logexceptions(also_stderr = True):
>       class ExceptHook:
>          def __init__(self, useStderr = False):
>             self.useStderr = useStderr
>          def __call__(self, etype, evalue, etb):
>             import traceback, string
>             tb = traceback.format_exception(*(etype, evalue, etb))
>             tb = map(string.rstrip, tb)
>             tb = string.join(tb, '\n')
>             for line in string.split(tb, '\n'):
>                syslog.syslog(line)
>                if self.useStderr:
>                   sys.stderr.write(line + '\n')
>       sys.excepthook = ExceptHook(also_stderr)
> Now, the downside to this is that currently the syslog module is entirely
> in C.  So either I'd need to implement the above in C, or I'd need to add a
> Python wrapper to the C module and use that.
> This would allow users to also log exceptions to syslog by doing:
>    import syslog
>    syslog.openlog('myprogram', syslog.LOG_PID, syslog.LOG_MAIL)
>    syslog.logexceptions()
> Thoughts?

I think this would be a great addition. I have to do similar things all 
of the time, although I never though of using sys.excepthook, for some 
reason. I'll have to steal your code in the meantime!

A simpler pure Python version would be:

from __future__ import print_function

def logexceptions(also_stderr=True):
     import sys
     import traceback
     import syslog
     def syslog_exception(etype, evalue, etb):
         # The result of traceback.format_exception might contain 

         # embedded newlines, so we have the nested loops. 

         for line in traceback.format_exception(etype, evalue, etb):
             for line in line.rstrip().split('\n'):
                 if also_stderr:
                     print(line, file=sys.stderr)
     sys.excepthook = syslog_exception


If you need any help implementing this in C, I'll assist (although I'm 
out of town for 2 weeks starting Thursday).


More information about the Python-ideas mailing list