How do I set the ident string when using logging.SysLogHandler in Python 2.6?

Trey Stout picture Trey Stout · Nov 23, 2010 · Viewed 8.6k times · Source

I have logging configured using logging.fileConfig(). I have a the root logger going to a handler that uses SysLogHandler('/dev/log', handlers.SysLogHandler.LOG_USER)

This all works perfectly well, and I see my log entries in /var/log/user.log

The question is how can I set the syslog ident string to something other than python? It appears the syslog module in the standard lib allows setting this when opening a log, but the logging handler doesn't offer this feature.

Would the solution be to subclass SysLogHandler and use the syslog library inside it's emit method? This is a unix only program, so using syslog directly doesn't pose a portability problem.

Answer

FirefighterBlu3 picture FirefighterBlu3 · Oct 26, 2013

This is a bit old but new information should be recorded here so people don't feel the need to write their own syslog handler.

Since Python 3.3, the SysLogHandler has a class attribute of .ident precisely for this purpose; the default for it is ''.

Example:

import logging
from logging.handlers import SysLogHandler

h = SysLogHandler(address=('some.destination.com',514), facility=SysLogHandler.LOG_LOCAL6)
h.setFormatter(
    logging.Formatter('%(name)s %(levelname)s %(message)s')
)
h.ident = 'conmon'

syslog = logging.getLogger('syslog')
syslog.setLevel(logging.DEBUG)
syslog.addHandler(h)

syslog.debug('foo syslog message')