Python
•
•
By Eric
Python 日誌記錄 (Logging):別再用 print 了
專業的程式都有 Log
使用 print 的缺點是無法分級、無法輕易開關、且無法同時輸出到螢幕與檔案。Python 的標準 logging 模組解決了這些問題。
基本設定:
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[logging.FileHandler("app.log"), logging.StreamHandler()]
)
logger = logging.getLogger(__name__)
這樣設定後,logger.info() 的訊息會同時出現在 Console 和 app.log 檔案中,且包含時間戳。在排查線上問題時,能夠透過 Log Level (DEBUG, INFO, WARNING, ERROR) 快速過濾資訊,是維運的救命稻草。