I can't get my head around Python's logging
module. My needs are very simple: I just want to log everything to syslog. After reading documentation I came up with this simple test script:
import logging
import logging.handlers
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
handler = logging.handlers.SysLogHandler()
my_logger.addHandler(handler)
my_logger.debug('this is debug')
my_logger.critical('this is critical')
But this script does not produce any log records in syslog. What's wrong?
I add a little extra comment just in case it helps anyone because I found this exchange useful but needed this little extra bit of info to get it all working.
To log to a specific facility using SysLogHandler you need to specify the facility value. Say for example that you have defined:
local3.* /var/log/mylog
in syslog, then you'll want to use:
handler = logging.handlers.SysLogHandler(address = ('localhost',514), facility=19)
and you also need to have syslog listening on UDP to use localhost instead of /dev/log.
Change the line to this:
This works for me
Here's the yaml dictConfig way recommended for 3.2 & later.
In log
cfg.yml
:Load the config using:
Configured both syslog & a direct file. Note that the
/dev/log
is OS specific.the above script will log to LOCAL0 facility with our custom "LOG_IDENTIFIER"... you can use LOCAL[0-7] for local purpose.
From https://github.com/luismartingil/per.scripts/tree/master/python_syslog
You should always use the local host for logging, whether to /dev/log or localhost through the TCP stack. This allows the fully RFC compliant and featureful system logging daemon to handle syslog. This eliminates the need for the remote daemon to be functional and provides the enhanced capabilities of syslog daemon's such as rsyslog and syslog-ng for instance. The same philosophy goes for SMTP. Just hand it to the local SMTP software. In this case use 'program mode' not the daemon, but it's the same idea. Let the more capable software handle it. Retrying, queuing, local spooling, using TCP instead of UDP for syslog and so forth become possible. You can also [re-]configure those daemons separately from your code as it should be.
Save your coding for your application, let other software do it's job in concert.