python-日誌學習(logging)

python logging:
英文原版:https://docs.python.org/2/howto/logging.html#logging-basic-tutorial
中文翻譯版:http://blog.csdn.net/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 的格式化選項

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章