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