Search code examples
pythonloggingsyslog

Syslog messages show up as "Unknown" when I use Python's logging.handlers.SysLogHandler


When I run this on my mac:

import logging.handlers
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

syslog_address = '/var/run/syslog'
logger.addHandler(logging.handlers.SysLogHandler(syslog_address))
logger.error("What the crap?")

It shows up like this in the syslog:

Oct 18 19:02:06 nick Unknown[4294967295] <Error>: What the crap?

Why is it Unknown? Shouldn't it be smart enough to name itself after the script's name?


Solution

  • To get what you need, you should add a formatter to the handler so you don't have to manually format every message yourself.

    import logging.handlers
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    
    syslog_address = '/var/run/syslog'
    
    handler = logging.handlers.SysLogHandler(syslog_address)
    # create the formatter
    formatter = logging.Formatter('%(name)s: [%(levelname)s] %(message)s')
    # plug this formatter into your handler(s)
    handler.setFormatter(formatter)
    
    logger.addHandler(handler)
    logger.error("What the crap?")
    

    You should now find that you see entries in syslog as you'd expect:

    Jul  4 14:34:40 ip-127-0-0-1 script_name.py: [ERROR] What the crap?