正在将函数输出打印到Syslog?

2024-10-01 13:44:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望将“check_call()”的“stdout”和“stderr”输出发送到Syslog。这可能吗?在

代码:

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)

Tags: 代码cmdnonefalseifdefcheckstderr
2条回答

是的,这是可能的,但是我认为您需要使用Popen而不是check_call,并将进程stdout和{}发送到正确配置的记录器。 这样的记录器将使用logging.handlers.SysLogHandler向您的syslog服务器发送消息。下面是如何创建这样一个记录器的简短示例:

import logging

handler = logging.handlers.SysLogHandler()
logger = logging.getLogger('myApplication')
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)

下面是一个如何将check_call替换为Popen并将数据发送到记录器的示例:

^{pr2}$

我在2017年遇到了这个问题,所以我认为继续为python3更新它可能是个好主意,因为解决方案需要稍作修改。为了能够利用Python 3中的SysLogHandler,您必须按如下方式调整代码:

 import logging
 import logging.handlers as handlers

 handler = handlers.SysLogHandler(address='/dev/log')
 logger = logging.getLogger('myApplication')
 logger.setLevel(logging.DEBUG)
 logger.addHandler(handler)

here所述,SysLogHandler

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.

相关问题 更多 >