作为一名开发人员,尝试从 php 转换为 python。目前正在尝试调试一个大约需要 45 分钟才能运行的 python 脚本。从命令行运行时还没有死掉。从 cron 运行时大约有一半的时间会死掉。
使用 php,我可以返回到它运行的盒子,检查运行时间的日志文件,并在脚本崩溃时查找/修复错误。 python 有类似的东西吗?
最佳答案
Python可以打印文件中的日志,但这不是您开箱即用的行为。默认情况下,它在 stderr 上打印日志级别等于或高于 WARNING 的日志:
import logging
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
运行此脚本时会发生以下情况:
$ python log.py
WARNING:root:warning
ERROR:root:error
CRITICAL:root:critical
$ python log.py 2>/dev/null # does not print anything
$
因此,如果您将 stderr 重定向到 cron 作业中的某个文件,您至少应该看到该文件中的警告和错误。如果您想轻松地直接登录到文件,可以使用 logging.basicConfig
:
import logging
# print log in example.log instead of the console, and set the log level to DEBUG (by default, it is set to WARNING)
logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
现在,如果您运行它,控制台中不应该再有任何输入,但所有内容都应该在 example.log
中:
$ python log.py
$ cat example.log
DEBUG:root:debug
INFO:root:info
WARNING:root:warning
ERROR:root:error
CRITICAL:root:critical
您将在logging HOWTO page中找到更多详细信息和配置选项。
关于php - Python 是否有像 PHP 一样的标准错误日志文件和 error_log 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48464630/