Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 576
Nick Retallack Avatar asked Oct 19 '11 02:10

Nick Retallack


2 Answers

It can be found all list which word matches what in the list you can find at this link

If you need more you can have a look further example:

from logging.handlers import SysLogHandler
import logging

def log(self, severity=logging.DEBUG, message=None):
    """
    Log utility for system wide logging needs
    @param severity Log severity
    @param message Log message
    @return
    """
    logger = logging.getLogger()
    logger.setLevel(severity)
    syslog = SysLogHandler(address="/dev/log")
    syslog.setFormatter(
          logging.Formatter("%(module)s-%(processName)s[%(process)d]: %(name)s: %(message)s")
    )
    logger.addHandler(syslog)
    logger.log(severity, message)

It is quite simple and I use this method as a global logging package in my projects.

like image 80
Fatih Karatana Avatar answered Sep 20 '22 20:09

Fatih Karatana


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?
like image 38
Splee Avatar answered Sep 18 '22 20:09

Splee