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

Python Interface กับรูทีนไลบรารี syslog UNIX


ในการรับข้อมูลไลบรารี syslog ของ UNIX เราจำเป็นต้องใช้โมดูล syslog ในโปรแกรมของเรา โมดูลนี้มี syslog มีโมดูลที่แตกต่างกันสำหรับไลบรารี syslog

ในการใช้โมดูลนี้ เราควรนำเข้าโดยใช้ −

import syslog

วิธีการมีดังนี้ −

วิธีการ syslog.syslog(ข้อความ) หรือ syslog.syslog(ลำดับความสำคัญ, ข้อความ)

วิธีนี้ใช้เพื่อส่งข้อความประเภทสตริงไปยังตัวบันทึกระบบ แต่ละข้อความมีความสำคัญ สามารถใช้อาร์กิวเมนต์ลำดับความสำคัญเพื่อกำหนดลำดับความสำคัญของข้อความที่กำหนดได้

วิธีการ syslog.openlog([ident[, logoption[, สิ่งอำนวยความสะดวก]]])

เมธอดนี้ใช้เพื่อบันทึกตัวเลือกของการเรียก syslog ที่ตามมา อาร์กิวเมนต์ ident เป็นอาร์กิวเมนต์ประเภทสตริง มันแสร้งทำเป็นทุกข้อความ

วิธีการ syslog.closelog()

วิธีนี้ใช้เพื่อรีเซ็ตโมดูล syslog เมื่อนำเข้าโมดูล โมดูลนี้จะเปลี่ยนเป็นสถานะนั้น

วิธีการ syslog.setlogmask(maskpri)

วิธีนี้ใช้เพื่อตั้งค่ามาสก์ลำดับความสำคัญเป็น maskpri ซึ่งจะคืนค่ามาสก์ก่อนหน้า เมื่อไม่มีลำดับความสำคัญ maskpri จะถูกละเว้น

โค้ดตัวอย่าง

import syslog, sys
syslog.openlog(sys.argv[0])
syslog.syslog(syslog.LOG_NOTICE, "This is a Log Notice")
syslog.openlog()

ผลลัพธ์

$ python3 posix_example.py
$ sudo cat /var/log/syslog
Oct  7 00:05:23 unix_user-VirtualBox anacron[14271]: Job `cron.daily' terminated
Oct  7 00:05:23 unix_user-VirtualBox anacron[14271]: Normal exit (1 job run)
Oct  7 00:17:01 unix_user-VirtualBox CRON[14396]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)
Oct  7 00:22:35 unix_user-VirtualBox gnome-software[1599]: no app for changed ubuntu-dock@ubuntu.com
Oct  7 00:22:35 unix_user-VirtualBox gnome-software[1599]: no app for changed ubuntu-appindicators@ubuntu.com
Oct  7 00:22:36 unix_user-VirtualBox gnome-shell[1296]: [AppIndicatorSupport-DEBUG] Registering StatusNotifierItem :1.59/org/ayatana/NotificationItem/software_update_available
Oct  7 00:22:37 unix_user-VirtualBox gvfsd-metadata[3664]: g_udev_device_has_property: assertion 'G_UDEV_IS_DEVICE (device)' failed
Oct  7 00:22:37 unix_user-VirtualBox gvfsd-metadata[3664]: g_udev_device_has_property: assertion 'G_UDEV_IS_DEVICE (device)' failed
Oct  7 00:25:47 unix_user-VirtualBox snapd[5511]: storehelpers.go:398: cannot refresh: snap has no updates available: "core", "gnome-3-26-1604", "gnome-calculator", "gnome-characters", "gnome-logs", "gnome-system-monitor", "gtk-common-themes"
Oct  7 00:25:47 unix_user-VirtualBox snapd[5511]: autorefresh.go:387: auto-refresh: all snaps are up-to-date
Oct  7 00:27:32 unix_user-VirtualBox example.py: This is a Log Notice