Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Giao diện Python đến thư viện syslog kiểu UNIX

Để lấy thông tin thư viện syslog của UNIX, chúng ta cần dùng module syslog trong chương trình. Module này có các phương thức cho thư viện syslog.

Để dùng module này, nên nhập bằng:

import syslog

Các phương thức như sau:

Phương thức syslog.syslog(message) hoặc syslog.syslog(priority, message)

Phương thức này dùng để gửi thông điệp dạng chuỗi (string) đến hệ thống logger (syslog). Mỗi thông điệp có một độ ưu tiên (priority). Đối số priority có thể dùng để thiết lập độ ưu tiên cho thông điệp.

Phương thức syslog.openlog([ident[, logoption[, facility]]])

Phương thức này dùng để thiết lập các tùy chọn ghi log cho các lần gọi syslog tiếp theo. Đối số ident là chuỗi; nó được tiền tố vào mọi thông điệp.

Phương thức syslog.closelog()

Phương thức này dùng để reset module syslog. Khi module được nhập, module chuyển về trạng thái đó.

Phương thức syslog.setlogmask(maskpri)

Phương thức này dùng để thiết lập mặt nạ ưu tiên (priority mask) thành maskpri, trả về giá trị mặt nạ trước đó. Khi không có độ ưu tiên, maskpri bị bỏ qua.

Mã ví dụ

import syslog, sys

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

Kết quả

$ 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