完成修改后,尝试在错误的数据上使用这些代码:
>>> import report >>> a = report.read_portfolio('Data/missing.csv') Row 4: Bad row: ['MSFT', '', '51.23'] Row 7: Bad row: ['IBM', '', '70.44'] >>>如果你什么都不做,则只会获得 WARNING 级别以上的日志消息。输出看起来像简单的打印语句。但是,如果你配置了日志模块,你将会获得有关日志级别,模块等其它信息。请按以下步骤操作查看:
>>> import logging >>> logging.basicConfig() >>> a = report.read_portfolio('Data/missing.csv') WARNING:fileparse:Row 4: Bad row: ['MSFT', '', '51.23'] WARNING:fileparse:Row 7: Bad row: ['IBM', '', '70.44'] >>>你会发现,看不到来自于 log.debug() 操作的输出。请按以下步骤修改日志级别(译注:因为日志配置是一次性的,所以该操作需要重启命令行窗口):
>>> logging.getLogger('fileparse').level = logging.DEBUG >>> a = report.read_portfolio('Data/missing.csv') WARNING:fileparse:Row 4: Bad row: ['MSFT', '', '51.23'] DEBUG:fileparse:Row 4: Reason: invalid literal for int() with base 10: '' WARNING:fileparse:Row 7: Bad row: ['IBM', '', '70.44'] DEBUG:fileparse:Row 7: Reason: invalid literal for int() with base 10: '' >>>只留下 critical 级别的日志消息,关闭其它级别的日志消息。
>>> logging.getLogger('fileparse').level=logging.CRITICAL >>> a = report.read_portfolio('Data/missing.csv') >>> 练习 8.3:向程序添加日志要添加日志到应用中,你需要某种机制来实现在主模块中初始化日志。其中一种方式使用看起来像下面这样的代码:
# This file sets up basic configuration of the logging module. # Change settings here to adjust logging output as needed. import logging logging.basicConfig( filename = 'app.log', # Name of the log file (omit to use stderr) filemode = 'w', # File mode (use 'a' to append) level = logging.WARNING, # Logging level (DEBUG, INFO, WARNING, ERROR, or CRITICAL) )再次说明,你需要将日志配置代码放到程序启动步骤中。例如,将其放到 report.py 程序里的什么位置?
注:完整翻译见 https://github.com/codists/practical-python-zh