Python logging使用
生活随笔
收集整理的這篇文章主要介紹了
Python logging使用
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Python logging使用
快速配置
# -*- coding:utf-8 -*- import logging# 默認(rèn)配置root logger logging.basicConfig(filename='root.log', level=logging.INFO)# 寫入文件中 logging.debug('debug message') # 低于INFO級(jí)別,不輸出 logging.info('info message') logging.warn('warn message') logging.error('error message') logging.critical('critical message')通過Logger配置
當(dāng)程序模塊眾多時(shí),每個(gè)模塊可以分別創(chuàng)建logger,更將靈活;
一個(gè)logger可以有多個(gè)FileHandler;
Logger的層級(jí)關(guān)系
# -*- encoding:utf-8 -*- import logging import sys# logging默認(rèn)有root logger print logging.root print logging.getLogger() print logging.getLogger() == logging.root# 沒有handler print logging.root.handlers# 一旦執(zhí)行這個(gè),就會(huì)自動(dòng)添加stdout到handler中,下面兩行等價(jià) # logging.basicConfig(stream=sys.stdout, level=logging.WARN) logging.warn('warn message') print logging.root.handlers# 新建的logger,默認(rèn)是root的孩子 child = logging.getLogger('child') print child.parent print child.handlers# 消息會(huì)自低向頂傳到root # 一條標(biāo)準(zhǔn)輸出來自root child.error('error message')child.addHandler(logging.StreamHandler())# 一條標(biāo)準(zhǔn)輸出來自child;一條標(biāo)準(zhǔn)輸出來自root child.error('error message')# 自動(dòng)解析層次結(jié)果;root->child->descendant descendant = logging.getLogger('child.descendant')Flask logging配置
# 需要:將所有輸出都重定向到一個(gè)文件中; # 查看flask logging文檔 # Werkzeug logs basic request/response information to the 'werkzeug' logger. # 所以需要在root logger指定日志文件handler;讓W(xué)erkzeug接收的record向上傳遞到root中的handlerlogging.basicConfig(filename=filename, filemode='w', level=logging.INFO)# 同時(shí),程序運(yùn)行時(shí)可能會(huì)報(bào)錯(cuò),需要將stdout與stderr重定向到日志文件中。 # 不能再使用handler,因?yàn)閟tdout也是filehandler,不存在handler綁定logger的 # 似乎更好的選擇是用兩個(gè)日志文件: nohup command > error.log 2>&1 & sys.stdout = sys.stderr = open(filename, "a")參考文獻(xiàn)
python logging模塊使用教程
Python root logger 解密
Logging Doc
轉(zhuǎn)載于:https://www.cnblogs.com/yuanquanxi/p/10883700.html
總結(jié)
以上是生活随笔為你收集整理的Python logging使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (十五)java B2B2C 多级Spr
- 下一篇: websocket python爬虫_p