Python logging模塊
Logging日志一共五個(gè)級(jí)別
- debug : 打印全部的日志,詳細(xì)的信息,通常只出現(xiàn)在診斷問(wèn)題上
- info : 打印info,warning,error,critical級(jí)別的日志,確認(rèn)一切按預(yù)期運(yùn)行
- warning : 打印warning,error,critical級(jí)別的日志,一個(gè)跡象表明,一些意想不到的事情發(fā)生了,或表明一些問(wèn)題在
- 不久的將來(lái)(例如。磁盤空間低”),這個(gè)軟件還能按預(yù)期工作
- error : 打印error,critical級(jí)別的日志,更嚴(yán)重的問(wèn)題,軟件沒(méi)能執(zhí)行一些功能
- critical : 打印critical級(jí)別,一個(gè)嚴(yán)重的錯(cuò)誤,這表明程序本身可能無(wú)法繼續(xù)運(yùn)行
日志級(jí)別:CRITICAL >ERROR> WARNING > INFO> DEBUG> NOTSET
logging日志設(shè)置以及使用
import logging
# 日志記錄最低輸出級(jí)別設(shè)置
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# Logging記錄到文件
fh = logging.FileHandler("test.log", mode='w')
logger.addHandler(fh) # 將logger添加到handler里面
#### Logging記錄格式以及設(shè)置
formatter = logging.Formatter("%(asctime)s - %(message)s") # 記錄時(shí)間和消息
fh.setFormatter(formatter) # 此處設(shè)置handler的輸出格式
# Logging使用
logger.info("this is info")
logger.debug("this is debug")
logger.warning("this is warning")
logging.error("this is error")
logger.critical("this is critical")
輸出test.log
2019-03-18 21:39:37,260 - this is info
2019-03-18 21:39:37,260 - this is debug
2019-03-18 21:39:37,260 - this is warning
2019-03-18 21:39:37,260 - this is error
2019-03-18 21:39:37,260 - this is critical
yaml配置logger
- 文件目錄
-----app
│ │
│ factoty.py
-----config
| |
| config.yaml
| logging.yaml
run.py
- 編寫logging.yaml
version: 1
disable_existing_loggers: False
# 定義日志輸出格式,可以有多種格式輸出
formatters:
simple:
format: "%(message)s"
error:
format: "%(asctime)s [%(name)s] [%(levelname)s] :%(levelno)s: %(message)s"
# 定義不同的handler,輸出不同等級(jí)的日志消息
handlers:
console:
class: logging.StreamHandler # 輸出到控制臺(tái)
level: DEBUG
formatter: simple
stream: ext://flask.logging.wsgi_errors_stream # 監(jiān)聽(tīng)flask日志
info_file_handler:
class: logging.handlers.RotatingFileHandler # 輸出到文件
level: INFO
formatter: simple
filename: ./logs/info.log
maxBytes: 10485760 # 10MB
backupCount: 20 #most 20 extensions
encoding: utf8
error_file_handler:
class: logging.handlers.RotatingFileHandler # 輸出到文件
level: ERROR
formatter: simple
filename: ./logs/errors.log
maxBytes: 10485760 # 10MB
backupCount: 20
encoding: utf8
# 啟用handler
root:
level: INFO
handlers: [console,info_file_handler,error_file_handler]
- 編寫Flask config.yaml
COMMON: &common
# app設(shè)置
DEBUG: False
TESTING: False
THREADED: False
SECRET_KEY: insecure
# 日志配置文件路徑
LOGGING_CONFIG_PATH: ./config/logging.yaml
# 日志文件存放位置
LOGGING_PATH: ./logs
DEVELOPMENT: &development
<<: *common
DEBUG: True
ENV: dev
TESTING: &testing
<<: *common
ENV: test
TESTING: True
PRODUCTION: &production
<<: *common
ENV: prod
SECRET_KEY: shouldbereallysecureatsomepoint
- 運(yùn)行文件(run.py)
from app import factory
app = factory.create_app(config_name='DEVELOPMENT')
app.logger.info('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')
if __name__ == "__main__":
app.run()
結(jié)果(自動(dòng)創(chuàng)建日志)
