Python 標準庫中的 logging 模塊提供了一套標準的 API 來處理日志信息的打印。
import logginglogging.basicConfig( level = logging.DEBUG, format = '%(asctime)s [%(threadName)s] (%(filename)s:%(lineno)d) %(levelname)s - %(message)s', datefmt = '%Y-%m-%d %H:%M:%S', filename = 'myapp.log',)logging.debug('This is a debug message')logging.info('This is an info message')logging.warning('This is a warning message')
在 myapp.log 中打印出的日志如下:
2015-03-11 15:54:34 [MainThread] (logging_demo.py:10) DEBUG - This is a debug message2015-03-11 15:54:34 [MainThread] (logging_demo.py:11) INFO - This is an info message2015-03-11 15:54:34 [MainThread] (logging_demo.py:12) WARNING - This is a warning message
logging.basicConfig 函數(shù)的參數(shù)說明:
| 參數(shù) | 說明 |
| filename | 用戶創(chuàng)建 FileHandler 實例的文件名 |
| filemode | 日志文件的打開模式,默認為 'a' |
| format | 日志的輸出格式 |
| datefmt | 時間的輸出格式 |
| level | 日志級別,大小關(guān)系為 CRITICAL(50) > ERROR(40) > WARNING(30) > INFO(20) > DEBUG(10) > NOTSET(0) |
| stream | 用于初始化 StreamHandler 的流,此參數(shù)與 filename 一起指定時,會被忽略掉 |
logging 中的格式化符號:
| 符號 | 說明 |
| %(asctime)s | 時間 |
| %(filename)s | 文件名 |
| %(funcName)s | 函數(shù)名 |
| %(levelname)s | 日志級別值 |
| %(levelno)s | 日志級別 |
| %(lineno)d | 行號 |
| %(module)s | 模塊 |
| %(message)s | 日志消息 |
| %(name)s | 日志名稱 |
| %(pathname)s | logger的名稱 |
| %(PRocess)d | 進程ID |
| %(processName)s | 進程名 |
| %(thread)d | 線程ID |
| %(threadName)s | 線程名 |
新聞熱點
疑難解答