php - Python 是否有像 PHP 一样的标准错误日志文件和 error_log 函数?

标签 php python error-logging

作为一名开发人员,尝试从 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/

相关文章:

php - MySQL where like with multiple words and order by weight

php - 值得在我的服务器上运行 memcache 吗?

javascript - 在数据库中临时存储信用卡信息

php - Elasticsearch PHP fatal error :未捕获的TypeError:参数1

python - 在 macOS 上为 MoviePy 安装 ffmpeg 失败并出现 SSL 错误

java - 如果发生异常,则转储调试日志

Python 日志记录 - 如何继承根记录器级别和处理程序

python - 如何在python中求解积分方程?

python - 深拷贝和迭代返回不同的结果

Java - 记录异常