Reputation: 1902
I want to make it so that the "stdout" and "stderr" output from "check_call()" is sent to Syslog. Is this possible?
Code:
def command(cmd, err=None, ifexit=False):
try:
check_call(shlex.split(cmd), stdout=null, stderr=null)
except CalledProcessError:
if err != None:
print err
if ifexit == True:
exit(1)
Upvotes: 2
Views: 3769
Reputation: 590
I came across this in 2017 so I thought it might be good to go ahead and update this for Python 3 as the solution needs slight modification. In order to be able to utilize the SysLogHandler
in Python 3, you will have to adjust the code as follows:
import logging
import logging.handlers as handlers
handler = handlers.SysLogHandler(address='/dev/log')
logger = logging.getLogger('myApplication')
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
As detailed here, SysLogHandler
class
Returns a new instance of the SysLogHandler class intended to communicate with a remote Unix machine whose address is given by address in the form of a (host, port) tuple. If address is not specified, ('localhost', 514) is used. The address is used to open a socket. An alternative to providing a (host, port) tuple is providing an address as a string, for example ‘/dev/log’. In this case, a Unix domain socket is used to send the message to the syslog.
Upvotes: 1
Reputation: 18029
Yes it is possible, but i think you would need to use Popen
instead of check_call
, and send the process' stdout
and stderr
to a properly configured logger.
Such a logger would use logging.handlers.SysLogHandler
to send messages to your syslog server. Here is a short example of how such a logger could be created:
import logging
handler = logging.handlers.SysLogHandler()
logger = logging.getLogger('myApplication')
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
And here is an example of how you could replace check_call
with Popen
and send the data to the logger:
process = Popen(shlex.split(cmd), stdout=PIPE, stderr=PIPE)
# Popen.wait() waits for the command to complete and
# returns the command's return code
if process.wait() != 0:
print "AN ERROR OCCURED"
logger.error(process.stderr)
logger.info(process.stdout)
Upvotes: 2