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?
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With