给简单脚本增加日志功能-python cookbook(第3版)高清中文完整版

时间:2024-06-29 23:06:48
【文件属性】:

文件名称:给简单脚本增加日志功能-python cookbook(第3版)高清中文完整版

文件大小:4.84MB

文件格式:PDF

更新时间:2024-06-29 23:06:48

python cookbook 第3版 高清 中文完整版

13.11 给简单脚本增加日志功能 问题 You want scripts and simple programs to write diagnostic information to log files. 解决方案 The easiest way to add logging to simple programs is to use the logging module. For example: import logging def main(): # Configure the logging system logging.basicConfig( filename=’app.log’, level=logging.ERROR ) # Variables (to make the calls that follow work) hostname = ‘www.python.org’ item = ‘spam’ filename = ‘data.csv’ mode = ‘r’ # Example logging calls (insert into your program) logging.critical(‘Host %s unknown’, hostname) logging.error(“Couldn’t find %r”, item) logging.warning(‘Feature is deprecated’) logging.info(‘Opening file %r, mode=%r’, filename, mode) logging.debug(‘Got here’) if __name__ == ‘__main__’: main() The five logging calls (critical(), error(), warning(), info(), debug()) represent different severity levels in decreasing order. The level argument to basicConfig() is a filter. All messages issued at a level lower than this setting will be ignored. The argument to each logging operation is a message string followed by zero or more arguments. When making the final log message, the % operator is used to format the message string using the supplied arguments. If you run this program, the contents of the file app.log will be as follows: CRITICAL:root:Host www.python.org unknown ERROR:root:Could not find ‘spam’ If you want to change the output or level of output, you can change the parameters to the basicConfig() call. For example: logging.basicConfig(


网友评论