如何将函数输出打印到Syslog?

2 投票
2 回答
3704 浏览
提问于 2025-04-17 01:19

我想把“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)

2 个回答

1

我在2017年遇到过这个问题,所以我觉得有必要为Python 3更新一下这个内容,因为解决方案需要稍微调整一下。为了在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)

详细信息可以在这里找到,关于SysLogHandler类的说明:

这个SysLogHandler类的实例是用来和远程的Unix机器进行通信的,机器的地址是通过一个(host, port)的元组来给出的。如果没有指定地址,默认使用('localhost', 514)。这个地址用于打开一个套接字。你也可以用字符串形式提供地址,比如‘/dev/log’,在这种情况下,会使用Unix域套接字将消息发送到syslog。

2

是的,这是可能的。不过我觉得你需要用 Popen 来代替 check_call,并把这个进程的 stdout(标准输出)和 stderr(错误输出)发送到一个配置好的日志记录器。这个日志记录器会使用 logging.handlers.SysLogHandler 来把信息发送到你的系统日志服务器。下面是一个简单的例子,展示了如何创建这样的日志记录器:

import logging

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

接下来,这里有一个例子,说明你如何用 Popen 替换 check_call,并把数据发送到日志记录器:

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)

撰写回答