Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log to journald (systemd) via Python?

I would like logging.info() to go to journald (systemd).

Up to now I only found python modules which read journald (not what I want) or modules which work like this: journal.send('Hello world')

like image 831
guettli Avatar asked Jan 04 '16 09:01

guettli


People also ask

How do I view Journald logs?

Basic Log Viewing. To see the logs that the journald daemon has collected, use the journalctl command. When used alone, every journal entry that is in the system will be displayed within a pager (usually less ) for you to browse.

How do I view systemd logs?

Logs collected by systemd can be viewed by using journalctl. The journal is implemented with the journald daemon and it retrieves messages from the kernel, systemd services, and other sources. These logs are gathered in a central location, which makes it easy to review.

Is Journald part of systemd?

systemd-journald is a system service that collects and stores logging data. It creates and maintains structured, indexed journals based on logging information that is received from a variety of sources: Kernel log messages, via kmsg. Simple system log messages, via the libc syslog(3) call.


3 Answers

python-systemd has a JournalHandler you can use with the logging framework.

From the documentation:

import logging
from systemd.journal import JournalHandler

log = logging.getLogger('demo')
log.addHandler(JournalHandler())
log.setLevel(logging.INFO)
log.info("sent to journal")
like image 55
martineg Avatar answered Oct 02 '22 07:10

martineg


An alternative to the official package, the systemd package works with python 3.6. Its source is also on github.

The implementation is a mirror of the official lib, with some minor changes:

import logging
from systemd import journal

log = logging.getLogger('demo')
log.addHandler(journal.JournaldLogHandler())
log.setLevel(logging.INFO)
log.info("sent to journal")

or for an even shorter method:

from systemd import journal

journal.write("Hello Lennart")
like image 45
bschlueter Avatar answered Oct 02 '22 07:10

bschlueter


This is a solution without third party modules. It works fine for me and the messages show up in journald.

import logging
import sys

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# this is just to make the output look nice
formatter = logging.Formatter(fmt="%(asctime)s %(name)s.%(levelname)s: %(message)s", datefmt="%Y.%m.%d %H:%M:%S")

# this logs to stdout and I think it is flushed immediately
handler = logging.StreamHandler(stream=sys.stdout)
handler.setFormatter(formatter)
logger.addHandler(handler)

logger.info('test')
like image 6
Joe Avatar answered Oct 04 '22 07:10

Joe