Python Interface to UNIX syslog library routines

PythonProgrammingServer Side Programming

To get the UNIX syslog library information, we need to use the syslog module into our programs. This module has syslog has different modules for the syslog library.

To use this module, we should import it using −

import syslog

The methods are like below −

Method syslog.syslog(message) or syslog.syslog(priority, message)

This method is used to send a string type message to the system logger. Each message has a priority. The priority argument can be used to set the priority of the given message.

Method syslog.openlog([ident[, logoption[, facility]]])

This method is used to logging options of subsequent syslog calls. The ident argument is a string type argument; it is pretended to every message.

Method syslog.closelog()

This method is used to reset the syslog module. When the module is imported, this module turns into that state.

Method syslog.setlogmask(maskpri)

This method is used to set the priority mask to maskpri, it returns the previous mask value. When there is no priority, the maskpri is ignored.

Example Code

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

Output

$ 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
raja
Published on 31-Oct-2018 13:42:36
Advertisements