python logging:
英文原版:https://docs.python.org/2/howto/logging.html#logging-basic-tutorial
中文翻译版:http://blog.youkuaiyun.com/tuxl_c_s_d_n/article/details/44892599
日志是用来追踪程序运行中的状态,可以选择在控制台打印出来,也可以选择存在一个Log文件中。
默认情况下python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET),默认的日志格式为日志级别:Logger名称:用户输出消息。(root部分)
WARNING:root:This is warning message
WARNING:root:This is warning message
ERROR:root:This is error message
CRITICAL:root:This is critical message
The default level is WARNING, which means that only events of this level and above will be tracked, unless the logging package is configured to do otherwise.
日志的格式化输出和root部分:
Logging to a file
将日志输出到文件中:
一个简单的例子:
import logging
logging.basicConfig(filename=’./just_a_try.log’,level=logging.DEBUG)
logging.debug(‘This message should go to the log file’)
logging.info(‘So should this’)
logging.warning(‘And this, too’)
logging.basicConfig参数:
level:设置logging水平,超过(包含)这个级别的日志将会被处理。
此外,也可以在命令行 python try_log.py --log=INFO 设置logging level
为了在程序中识别出传入的level参数,使用:
getattr(logging, loglevel.upper())
命令行:python try_log.py --log=DEBUG
代码:
import logging
loglevel = “DEBUG” #从命令行参数中解析
numeric_level = getattr(logging, loglevel.upper(), None) # 获取对象object的属性或者方法,存在则打印,不存在,打印出默认值,默认值可选。
if not isinstance(numeric_level, int):
raise ValueError(‘Invalid log level: %s’ % loglevel)
print “numeric_level is: {}”.format(numeric_level)
print “loglevel is: {}”.format(loglevel)
logging.basicConfig(filename=’./just_a_try.log’,level=numeric_level)
logging.debug(‘This message should go to the log file’)
logging.info(‘So should this’)
logging.warning(‘And this, too’)
basicConfig() 这个函数必选在debug(), info() 等函数之前调用。这个是配置项,对后续的操作会产生影响。
假如你多次运行这这个程序,那边日志信息会不断的追加到example.log文件中。假如你希望每次日志输出都会覆盖掉前面输出的内容,那么你可以使用filemode 选项。filemode=‘w’,以写的方式创建日志文件。
此外,要记录变量信息,可以使用格式化字符串作为描述信息,并将变量参数附加到后面的参数列表中。比如说:
import logging
logging.warning(’%s before you %s’, ‘Look’, ‘leap!’)
将会显示
WARNING:root:Look before you leap!
通过使用%-style的格式化字符串信息,变量被合并到了日志信息中。logging模块提供了比如 str.format() 和string.Template 的格式化选项