文章来源:微点阅读 https://www.weidianyuedu.com
作为经验丰富的开发人员,即便你编写了清晰易读的代码,并对代码进行了全方位的测试,但在某些时候程序还是会不可避免地出现一些奇怪的 Bug,这时候你就需要以某种方式 Debug。不少程序员喜欢使用一堆 print 语句来查看代码运行情况。这种方法有点低级,太傻瓜了;实际上有很多更好的方法来帮你定位代码中的问题,我们将在本文中介绍这些方法。
使用 Logging 模块
如果你编写的应用程序没有使用日志功能,那你终究会后悔没有及时用它的。如果应用程序中没有打印任何运行日志,就很难对程序错误进行故障定位及排除。幸运的是在 Python 中,我们很容易配置基本的日志模块:
import logginglogging.basicConfig( filename="application.log", level=logging.WARNING, format= "[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s", datefmt="%H:%M:%S")logging.error("Some serious error occurred.")logging.warning("Function you are using is deprecated.")
这就是开始将日志写入文件所需的全部操作,使用时,你可以通过
logging.getLoggerClass().root.handlers[0].baseFilename 找到文件的路径:
[12:52:35] {<stdin>:1} ERROR - Some serious error occurred.[12:52:35] {<stdin>:1} WARNING - Function you are using is deprecated.
这种设置看起来似乎已经足够好了(通常是这样),但是配置合理、格式清晰、可读性强的日志可以让你 Debug 起来更加轻松。优化日志配置的一种方法是使用.ini 或.yaml 配置文件。下面给你推荐一种配置示例:
version: 1disable_existing_loggers: trueformatters: standard: format: "[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s" datefmt: "%H:%M:%S"handlers: console: # handler which will log into stdout class: logging.StreamHandler level: DEBUG formatter: standard # Use formatter defined above stream: ext://sys.stdout file: # handler which will log into file class: logging.handlers.RotatingFileHandler level: WARNING formatter: standard # Use formatter defined above