为什么cron将Python的日志记录事件视为错误?

时间:2013-05-23 23:48:24

标签: python logging cron

我有一个非常简单的测试设置,包括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和/或log正在执行此操作,是否有解决方法?

1 个答案:

答案 0 :(得分:7)

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

请参阅logging.basicConfig() documentation

  

通过创建具有默认StreamHandler的{​​{1}}并将其添加到根记录器来进行日志系统的基本配置,

StreamHandler docs

  

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

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

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