【1】如何優雅的記錄日誌? logging
- 2019 年 10 月 10 日
- 筆記
版權聲明:本文為部落客原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
本文鏈接:https://blog.csdn.net/weixin_40313634/article/details/100782614
logging 模組
1 小例子: 在log文件輸出log
# 內置庫,不用安裝 import logging logging.basicConfig( filename="test.log", # 日誌保存文件 filemode="w", # 文件許可權 datefmt="%d-%M-%Y %H:%M:%S", # 列印的時間格式 format="%(asctime)s %(name)s:%(levelname)s:%(message)s", # 列印的日誌消息的格式 level=logging.DEBUG # 列印的日誌級別 >= 此級別的資訊會被列印:NOTSET、DEBUG、INFO、WARNING、ERROR、CRITICAL ) logging.debug('This is a debug message') logging.info('This is an info message') logging.warning('This is a warning message') logging.error('This is an error message') logging.critical('This is a critical message')
結果
# test.log 12-40-2019 14:40:17 root:DEBUG:This is a debug message 12-40-2019 14:40:17 root:INFO:This is an info message 12-40-2019 14:40:17 root:WARNING:This is a warning message 12-40-2019 14:40:17 root:ERROR:This is an error message 12-40-2019 14:40:17 root:CRITICAL:This is a critical message
異常消息捕獲
try: 10 / 0 except Exception as e: logging.exception(e)
參數
參數名 |
參數描述 |
---|---|
filename |
日誌輸出到文件的文件名 |
filemode |
文件模式,r[+]、w[+]、a[+] |
format |
日誌輸出的格式 |
datefat |
日誌附帶日期時間的格式 |
style |
格式佔位符,默認為 「%」 和 「{}」 |
level |
設置日誌輸出級別(默認:WARNING) |
2 分別在控制台、log 文件輸出不同的log消息
import logging import logging.handlers # 根logger對象,後面所有的日誌輸出都調的是它 logger = logging.getLogger("logger") # handler1: 輸出到螢幕; handler2: 輸出到文件 handler1 = logging.StreamHandler() handler2 = logging.FileHandler(filename="test.log", encoding="utf-8") # 螢幕列印error級別消息; 文件輸出DEBUG級別消息 handler1.setLevel(logging.ERROR) handler2.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s %(message)s") handler1.setFormatter(formatter) handler2.setFormatter(formatter) logger.addHandler(handler1) logger.addHandler(handler2) logger.info('This is an customer info message') logger.debug('This is a customer debug message') logger.warning('This is a customer warning message') logger.error('This is an customer error message') logger.critical('This is a custo