Logging คืออะไร
Logging คือการบันทึกเหตุการณ์ขณะโปรแกรมรัน ช่วย debug และติดตามปัญหาใน production
Module logging ใน Python
Python มี logging module built-in
import logging
5 ระดับความรุนแรง (Severity Levels)
- DEBUG: รายละเอียดสำหรับ diagnose ปัญหา
- INFO: ยืนยันว่าทำงานถูกต้อง
- WARNING: เหตุการณ์ที่อาจก่อปัญหาในอนาคต
- ERROR: ฟังก์ชันทำงานล้มเหลว
- CRITICAL: ปัญหาร้ายแรง โปรแกรมอาจหยุดทำงาน
Default: แสดงแค่ WARNING ขึ้นไป ต้อง config เพื่อแสดง DEBUG/INFO
ตัวอย่างพื้นฐาน
import logging
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')
Output
WARNING:root:This is a warning message
ERROR:root:This is an error message
CRITICAL:root:This is a critical message
การ Config แบบเต็มรูปแบบ
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('app.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
logger.debug('Debug message')
logger.info('Info message')
Best Practices
- ใช้ logger = logging.getLogger(__name__) ในแต่ละ module
- ตั้งค่า level และ format ใน entry point
- ใช้ structured logging (JSON) สำหรับ production
- หลีกเลี่ยง log ข้อมูล sensitive (password, token)