โมดูล syslog ให้ Python เขียน Log เข้า UNIX System Logger (syslogd) ได้โดยตรง
import syslog
เมธอดหลัก
syslog.syslog(message) / syslog.syslog(priority, message)
ส่งข้อความไป System Logger พร้อม Priority Level
syslog.openlog([ident[, logoption[, facility]]])
ตั้งค่า Logging Options สำหรับการเรียก syslog ต่อไป
ident: String นำหน้าทุกข้อความ (มักใช้ชื่อโปรแกรม)logoption: PID, CONS, NDELAY, PERROR, etc.facility: USER, LOCAL0-7, DAEMON, MAIL, etc.
syslog.closelog()
ปิดการเชื่อมต่อ syslog รีเซ็ตสถานะ
syslog.setlogmask(maskpri)
ตั้ง Priority Mask คืนค่า Mask เดิม
Priority Levels (Facility + Level)
| Constant | Level | ความหมาย |
|---|---|---|
| LOG_EMERG | 0 | System unusable |
| LOG_ALERT | 1 | Action needed immediately |
| LOG_CRIT | 2 | Critical conditions |
| LOG_ERR | 3 | Error conditions |
| LOG_WARNING | 4 | Warning conditions |
| LOG_NOTICE | 5 | Normal but significant |
| LOG_INFO | 6 | Informational |
| LOG_DEBUG | 7 | Debug-level messages |
โค้ดตัวอย่าง
import syslog import sys syslog.openlog(sys.argv[0]) # ident = script name syslog.syslog(syslog.LOG_NOTICE, "This is a Log Notice") syslog.closelog()
ผลลัพธ์ใน /var/log/syslog
Oct 7 00:27:32 unix_user-VirtualBox example.py: This is a Log Notice
Best Practices
- ใช้
openlog()ตั้ง ident ให้ชัดเจน - เลือก Priority ให้เหมาะสม (INFO สำหรับปกติ, ERR/WARNING สำหรับปัญหา)
- ปิดด้วย
closelog()เมื่อจบโปรแกรม - Production: ใช้
logging.handlers.SysLogHandlerแทน (ยืดหยุ่นกว่า)