1 python error-handling error-logging
我正在用 python 编写一个工具,我想将所有错误 - 并且仅将错误 - (未按应有的计算进行)放入单个日志文件中。此外,我希望在错误日志文件中为代码的每个部分提供不同的文本,以便使错误日志文件易于解释。我该如何编码?非常感谢谁能对此提供帮助!
查看 python 模块日志记录。这是一个核心模块,不仅可以在您自己的项目中统一日志记录,也可以在第三方模块中统一日志记录。
对于最小日志文件示例,这直接取自文档:
import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
Run Code Online (Sandbox Code Playgroud)
其结果是example.log:
DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too
Run Code Online (Sandbox Code Playgroud)
不过,我个人推荐使用 yaml 配置方法(需要pyyaml):
#logging_config.yml
version: 1
disable_existing_loggers: False
formatters:
standard:
format: '%(asctime)s [%(levelname)s] %(name)s - %(message)s'
handlers:
console:
class: logging.StreamHandler
level: INFO
formatter: standard
stream: ext://sys.stdout
file:
class: logging.FileHandler
level: DEBUG
formatter: standard
filename: output.log
email:
class: logging.handlers.SMTPHandler
level: WARNING
mailhost: smtp.gmail.com
fromaddr: to@address.co.uk
toaddrs: to@address.co.uk
subject: Oh no, something's gone wrong!
credentials: [email, password]
secure: []
root:
level: DEBUG
handlers: [console, file, email]
propagate: True
Run Code Online (Sandbox Code Playgroud)
然后使用,例如:
import logging.config
import yaml
with open('logging_config.yml', 'r') as config:
logging.config.dictConfig(yaml.safe_load(config))
logger = logging.getLogger(__name__)
logger.info("This will go to the console and the file")
logger.debug("This will only go to the file")
logger.error("This will go everywhere")
try:
list = [1, 2, 3]
print(list[10])
except IndexError:
logger.exception("This will also go everywhere")
Run Code Online (Sandbox Code Playgroud)
这打印:
2018-07-18 13:29:21,434 [INFO] __main__ - This will go to the console and the file
2018-07-18 13:29:21,434 [ERROR] __main__ - This will go everywhere
2018-07-18 13:29:21,434 [ERROR] __main__ - This will also go everywhere
Traceback (most recent call last):
File "C:/Users/Chris/Desktop/python_scratchpad/a.py", line 16, in <module>
print(list[10])
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)
而日志文件的内容是:
2018-07-18 13:35:55,423 [INFO] __main__ - This will go to the console and the file
2018-07-18 13:35:55,424 [DEBUG] __main__ - This will only go to the file
2018-07-18 13:35:55,424 [ERROR] __main__ - This will go everywhere
2018-07-18 13:35:55,424 [ERROR] __main__ - This will also go everywhere
Traceback (most recent call last):
File "C:/Users/Chris/Desktop/python_scratchpad/a.py", line 15, in <module>
print(list[10])
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)
当然,您可以添加或删除处理程序、格式化程序等,或者在代码中执行所有这些操作(请参阅 Python 文档),但每当我在项目中使用日志记录时,这都是我的起点。我发现将配置放在专用的配置文件中很有帮助,而不是通过定义登录代码来污染我的项目。
| 归档时间: |
|
| 查看次数: |
4658 次 |
| 最近记录: |