Package: cysystemd
Python systemd wrapper using CythonTable of contentsInstallationInstallation from binary wheelsInstallation from sourcesUsage examplesWriting to journaldLogging handler for python loggersystemd daemon notificationReading journaldReading all systemd recordsRead only cron logsPolling recordsjournald open modesjournald entryjournald readerAsyncio supportAsyncJournalReaderInstallationAll packages available ongithub releases.Installation from binary wheelswheels is now available for Python 3.7, 3.8, 3.9, 3.10, 3.11
forx86_64andarm64pythonn3.9-mpipinstall\https://github.com/mosquito/cysystemd/releases/download/1.4.8/cysystemd-1.4.8-cp39-cp39-manylinux2014_x86_64.whlInstallation from sourcesYoumustinstallsystemd headersFor Debian/Ubuntu users:aptinstallbuild-essentiallibsystemd-devOn older versions of Debian/Ubuntu, you might also need to install:aptinstalllibsystemd-daemon-devlibsystemd-journal-devFor CentOS/RHELyuminstallgccsystemd-develAnd install it from pypipipinstallcysystemdUsage examplesWriting to journaldLogging handler for python loggerfromcysystemdimportjournalimportloggingimportuuidlogging.basicConfig(level=logging.DEBUG)logger=logging.getLogger()logger.addHandler(journal.JournaldLogHandler())try:logger.info("Trying to do something")raiseException('foo')except:logger.exception("Test Exception%s",1)systemd daemon notificationfromcysystemd.daemonimportnotify,Notification# Send READY=1notify(Notification.READY)# Send statusnotify(Notification.STATUS,"I'm fine.")# Send stoppingnotify(Notification.STOPPING)Write message into systemd journalfromcysystemdimportjournaljournal.write("Hello Lennart")# Or send structured datajournal.send(message="Hello Lennart",priority=journal.Priority.INFO,some_field='some value',)Reading journaldReading all systemd recordsfromcysystemd.readerimportJournalReader,JournalOpenModejournal_reader=JournalReader()journal_reader.open(JournalOpenMode.SYSTEM)journal_reader.seek_head()forrecordinjournal_reader:print(record.data['MESSAGE'])Read only cron logsfromcysystemd.readerimportJournalReader,JournalOpenMode,Rulerules=(Rule("SYSLOG_IDENTIFIER","CRON")&Rule("_SYSTEMD_UNIT","crond.service")|Rule("_SYSTEMD_UNIT","cron.service"))cron_reader=JournalReader()cron_reader.open(JournalOpenMode.SYSTEM)cron_reader.seek_head()cron_reader.add_filter(rules)forrecordincron_reader:print(record.data['MESSAGE'])Polling recordsfromcysystemd.readerimportJournalReader,JournalOpenModereader=JournalReader()reader.open(JournalOpenMode.SYSTEM)reader.seek_tail()poll_timeout=255whileTrue:reader.wait(poll_timeout)forrecordinreader:print(record.data['MESSAGE'])journald open modesCURRENT_USERLOCAL_ONLYRUNTIME_ONLYSYSTEMSYSTEM_ONLYfromcysystemd.readerimportJournalReader,JournalOpenModereader=JournalReader()reader.open(JournalOpenMode.CURRENT_USER)journald entryJournalEntry class has some special properties and methods:data- journal entry content (dict)date- entry timestamp (datetimeinstance)cursor- systemd identification bytes for this entryboot_id()- returns bootidget_realtime_sec()- entry epoch (float)get_realtime_usec()- entry epoch (intmicroseconds)get_monotonic_sec()- entry monotonic time (float)get_monotonic_usec()- entry monotonic time (intmicroseconds)__getitem__(key)- shoutcut forentry.data[key]journald readerJournalReader class has some special properties and methods:open(flags=JournalOpenMode.CURRENT_USER)- opening journald
with selected modeopen_directory(path)- opening journald from pathopen_files(*filename)- opening journald from filesdata_threshold- may be used to get or set the data field size threshold
for data returned by fething entry data.closed- returns True when journal reader closedlocked- returns True when journal reader lockedidle- returns True when journal reader openedseek_head- move reader pointer to the first entryseek_tail- move reader pointer to the last entryseek_monotonic_usec- seeks to the entry with the specified monotonic
timestamp, i.e. CLOCK_MONOTONIC. Since monotonic time restarts on every
reboot a boot ID needs to be specified as well.seek_realtime_usec- seeks to the entry with the specified realtime
(wallclock) timestamp, i.e. CLOCK_REALTIME. Note that the realtime clock
is not necessarily monotonic. If a realtime timestamp is ambiguous, it is
not defined which position is sought to.seek_cursor- seeks to the entry located at the specified cursor
(seeJournalEntry.cursor).wait(timeout)- It will synchronously wait until the journal gets
changed. The maximum time this call sleeps may be controlled with the
timeout_usec parameter.__iter__- returns JournalReader object__next__- callsnext()or raiseStopIterationnext(skip=0)- returns the nextJournalEntry. Theskipparameter skips some entries.previous(skip=0)- returns the previousJournalEntry.
Theskipparameter skips some entries.skip_next(skip)- skips next entries.skip_previous(skip)- skips next entries.add_filter(rule)- adding filter rule.
Seeread-only-cron-logsas example.clear_filter- reset all filtersfd- returns a special file descriptorevents- returnsEPOLLeventstimeout- returns internal timeoutprocess_events()- After each poll() wake-up process_events() needs
to be called to process events. This call will also indicate what kind of
change has been detected.get_catalog()- retrieves a message catalog entry for the current
journal entry. This will look up an entry in the message catalog by using
the “MESSAGE_ID=” field of the current journal entry. Before returning
the entry all journal field names in the catalog entry text enclosed in
“@” will be replaced by the respective field values of the current entry.
If a field name referenced in the message catalog entry does not exist,
in the current journal entry, the “@” will be removed, but the field name
otherwise left untouched.get_catalog_for_message_id(message_id: UUID)- works similar toget_catalog()but the entry is looked up by the specified
message ID (no open journal context is necessary for this),
and no field substitution is performed.Asyncio supportInitialasynciosupport for reading journal asynchronously.AsyncJournalReaderBlocking methods were wrapped by threads.
Methodwait()use epoll on journald file descriptor.importasyncioimportjsonfromcysystemd.readerimportJournalOpenModefromcysystemd.async_readerimportAsyncJournalReaderasyncdefmain():reader=AsyncJournalReader()awaitreader.open(JournalOpenMode.SYSTEM)awaitreader.seek_tail()whileawaitreader.wait():asyncforrecordinreader:print(json.dumps(record.data,indent=1,sort_keys=True))if__name__=='__main__':asyncio.run(main())