Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't python log exceptions to syslog (but then, it does?)

The documentation for the emit() function of Python 2.x SysLogHandler says:

The record is formatted, and then sent to the syslog server. If exception information is present, it is not sent to the server.

...why? The source doesn't tell me much. Did I miss something?

However, when I try the following code:

import logging
from logging.handlers import SysLogHandler

rootlogger = logging.getLogger()
rootlogger.setLevel(logging.DEBUG)
syslogh = SysLogHandler('/dev/log')
rootlogger.addHandler(syslogh)
# to see what's happening too
consoleh = logging.StreamHandler()
rootlogger.addHandler(consoleh)

# this appears in the log
rootlogger.info('foobar')
try:
    a = 42
    a / 0
except ZeroDivisionError as e:
    rootlogger.exception('myException!: {}'.format(e))

It does write the following to syslog:

May 7 16:25:59 localhost foobar
May 7 16:25:54 localhost myException!: integer division or modulo by zero#012Traceback (most recent call last):#012 File "syslogonly.py", line 16, in #012 a / 0#012ZeroDivisionError: integer division or modulo by zero

I am using rsyslog 8.4.2 on a Debian wheezy system.

Also, I am aware there are issues with multiline, but is this related?

like image 710
lorenzog Avatar asked Nov 27 '25 16:11

lorenzog


1 Answers

You're not calling Logger.emit(). You're calling Logger.exception(), which according to the documentation, always adds exception info to the message:

Logs a message with level ERROR on this logger. The arguments are interpreted as for debug(), except that any passed exc_info is not inspected. Exception info is always added to the logging message. This method should only be called from an exception handler.

I didn't dive into the source code to determine what calls emit() and under what circumstances, however.

like image 139
robobrobro Avatar answered Nov 29 '25 06:11

robobrobro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!