Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Logging ใน Python Program

Logging คืออะไร

Logging คือการบันทึกเหตุการณ์ขณะโปรแกรมรัน ช่วย debug และติดตามปัญหาใน production

Module logging ใน Python

Python มี logging module built-in

import logging

5 ระดับความรุนแรง (Severity Levels)

  1. DEBUG: รายละเอียดสำหรับ diagnose ปัญหา
  2. INFO: ยืนยันว่าทำงานถูกต้อง
  3. WARNING: เหตุการณ์ที่อาจก่อปัญหาในอนาคต
  4. ERROR: ฟังก์ชันทำงานล้มเหลว
  5. 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)