【问题标题】:Why is cron catching Python's logging events as errors?为什么 cron 将 Python 的日志记录事件捕获为错误?
【发布时间】:2019-10-02 19:48:10
【问题描述】:

我有一个非常简单的测试设置,其中包含 cron 和一个使用 logging 模块的 Python 脚本,而 cron 在遇到日志事件时表现异常。

crontab

* * * * * ~/test.py >> ~/test.log

~/test.py

​​>
#!/usr/bin/env python

import logging
logging.basicConfig(level=logging.DEBUG)

print 'Properly printed, to file'
logging.debug("Does not get printed, get's e-mailed as an error")
print 'Still running, though'

~/test.log

cron 运行后,日志中会填充以下两条消息:

Properly printed, to file
Still running, though

cron 错误邮件

另外,在 cron 运行后,我收到一条通知说我有新邮件:

From tomcat6@local  Thu May 23 16:35:01 2013
Date: Thu, 23 May 2013 16:35:01 -0700
From: root@local (Cron Daemon)
To: tomcat6@local
Subject: Cron <tomcat6@local> ~/test.py >> ~/test.log
Content-Type: text/plain; charset=UTF-8
Auto-Submitted: auto-generated
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/usr/local/tomcat6>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=tomcat6>
X-Cron-Env: <USER=tomcat6>

DEBUG:root:Does not get printed, get's e-mailed as an error

看起来这不是一个明确的错误,否则最终的“仍在运行...”消息将不会打印到~/test.log,对吧?

为什么 cron 和/或日志记录会这样做,是否有解决方法?

【问题讨论】:

    标签: python logging cron


    【解决方案1】:

    basicConfig() 设置的默认配置将消息记录到stderr,并且 cron 将任何输出到stderr 文件句柄解释为电子邮件值得;毕竟,你没有重定向它。

    logging.basicConfig() documentation

    通过创建带有默认FormatterStreamHandler 并将其添加到根记录器来对日志系统进行基本配置,

    还有StreamHandler docs:

    如果指定了stream,实例将使用它来记录输出;否则,将使用sys.stderr

    解决方法是不设置流处理程序,或选择不同的流,或选择要记录到的文件名:

    logging.basicConfig(level=logging.DEBUG, filename='/some/file/to/log/to')
    

    logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
    

    通过记录到stdout,您可以将记录信息写入与print() 相同的输出流。

    另一种解决方法是将stderr 重定向到stdout

    * * * * * ~/test.py >> ~/test.log 2>&1
    

    【讨论】:

    • 非常感谢。 2&>1 对我不起作用,但 2>&1 对我有用。
    • @AkalankaWeerasooriya:啊,这确实是一个错字,谢谢指出!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 2019-04-18
    • 2014-10-16
    • 1970-01-01
    相关资源
    最近更新 更多