文章目錄
前言
一、logging介紹
1.1 基本概念
1.2 使用場景
1.3 logging level(日志級別分類)
1.4 示例代碼
二、logging的三種配置方式
2.1 直接配置
2.2 從配置文件中讀取配置
2.3 從包含配置信息的字典配置
小結(jié)
參考文獻(xiàn)
前言
創(chuàng)作開始時間:2021年3月25日11:35:28
如題。之前其實寫過一篇logging博客,但是那時候不求甚解,所以不得勁。這里再仔細(xì)研究一下,并記錄之。
主要參考:
Logging HOWTO
一、logging介紹
1.1 基本概念
Logging is a means of tracking events that happen when some software runs. The software’s developer adds logging calls to their code to indicate that certain events have occurred. An event is described by a descriptive message which can optionally contain variable data (i.e. data that is potentially different for each occurrence of the event). Events also have an importance which the developer ascribes to the event; the importance can also be called the level or severity.
logging是一個追蹤軟件運行過程中發(fā)生事件的一種方式。
logging用level或者severity來表示事件的重要性。
1.2 使用場景
| 場景/需求 | 日志方式 |
|---|---|
| 記錄程序狀態(tài) | logging.info() 或者logging.debug() |
| 提出warning | logging.warning() |
| 報告error(錯誤) | Raise an exception |
| 處理/抑制error不報錯 | logging.error(), logging.exception() or logging.critical() |
1.3 logging level(日志級別分類)
| Level | 用法 |
|---|---|
| DEBUG | 調(diào)試需要的詳細(xì)信息 |
| INFO | 確認(rèn)程序正常工作 |
| WARNING | 程序仍舊正常工作,但是報警未來可能出現(xiàn)的問題(如空間不夠) |
| ERROR | 程序某些功能不能繼續(xù)運行 |
| CRITICAL | 非常嚴(yán)重的錯誤,程序無法繼續(xù)運行 |
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.
默認(rèn)是WARNING級別。
logging的兩種方式:
1.輸出到控制臺
2.輸出到日志文件
1.4 示例代碼
import os
# 路徑獲取
cur_dir = os.path.abspath(__file__).rsplit("/", 1)[0]
log_path = os.path.join(cur_dir, "example.log")
# encoding='utf-8'
logging.basicConfig(filename=log_path, level=logging.DEBUG,
filemode = 'w', format='%(levelname)s:%(asctime)s:%(message)s', datefmt='%Y-%d-%m %H:%M:%S')
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
logging.error('And non-ASCII stuff, too, like? resund and Malm?')
logging.critical("critical")
注意:
-有的python版本的logging.basicConfig()沒有encoding這個參數(shù)!
level=logging.DEBUG表明所有>= DEBUG 這個level的都會被輸出;
filemode = 'w'表示不會追加寫,而是會重新寫;
format='%(levelname)s:%(asctime)s:%(message)s'參考:https://docs.python.org/3/library/logging.html#logging.basicConfig
datefmt參考https://docs.python.org/3/library/time.html#time.strftime
二、logging的三種配置方式
2.1 直接配置
Creating loggers, handlers, and formatters explicitly using Python code that calls the configuration methods listed above.
下面這串代碼功能還挺強大:
1)可以輸出到控制臺(終端);
2)還可以同時寫入到文件,
3)而且配置也很方便,功能挺強大的
以下供參考。
logger.setLevel(logging.DEBUG)
# set two handlers
log_file = "{}.log".format(__file__)
# rm_file(log_file)
fileHandler = logging.FileHandler(os.path.join(cur_dir, log_file), mode = 'w')
fileHandler.setLevel(logging.DEBUG)
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.DEBUG)
# set formatter
formatter = logging.Formatter('[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
consoleHandler.setFormatter(formatter)
fileHandler.setFormatter(formatter)
# add
logger.addHandler(fileHandler)
logger.addHandler(consoleHandler)
logger.info("test")
這個很好理解的,尤其是看了:
https://docs.python.org/3/howto/logging.html
之后,是真的好理解,所以這里就不多講了。而且vscode可以一鍵直接點到第三方庫的函數(shù)(比如logging.Formatter)里面去看,里面的注釋也很豐富。所以這里就不多解釋了。
注意: 后面兩種就不解讀了,有一種我覺得就已經(jīng)很簡潔,也夠用了。所以后續(xù)更新再說。
2.2 從配置文件中讀取配置
Creating a logging config file and reading it using the fileConfig() function.
2.3 從包含配置信息的字典配置
Creating a dictionary of configuration information and passing it to the dictConfig() function.
版權(quán)聲明:本文為CSDN博主「宇內(nèi)虹游」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請附上原文出處鏈接及本聲明。