Search code examples
pythonloggingsyslog

Printing Function Output to Syslog?


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)

Solution

  • 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)