1

This is the python I am using.

$ python3 --version
Python 3.5.2

This is the test code after some googling (How to log to journald (systemd) via Python?). I am trying to use journal log.

#!/usr/bin/python3

import logging
from systemd.journal import JournalHandler

log = logging.getLogger('test')
log.addHandler(JournalHandler())
log.setLevel(logging.DEBUG)
log.warning("warn")
log.info("info")
log.error("error")
log.debug("debug")

I am expecting to see in the log something like:

WARNING: warn
INFO: info
ERROR: error
DEBUG: debug

But this is what actually shows:

Nov 22 09:29:56 host1 ./test_log.py[8997]: warn
Nov 22 09:29:56 host1 ./test_log.py[8997]: info
Nov 22 09:29:56 host1 ./test_log.py[8997]: error
Nov 22 09:29:56 host1 ./test_log.py[8997]: debug

There is no log level prefixing the log message. Thanks for the help.

More info,

I also try formatting.

logging.basicConfig(format='%(levelname)s %(message)s')

Then on stdout, I could see log level but still not in journal.

Community
  • 1
  • 1
user180574
  • 5,681
  • 13
  • 53
  • 94

1 Answers1

6

Your basicConfig statement will create a StreamHandler, the format you set here will only be for the log you get on stdout. Look at the docs for Formatter objects which says If no fmt is specified, '%(message)s' is used.. Therefore you have to create a separate Formatter and use setFormatter on the JournalHandler to get your desired output.

A basic modification of your code below:

#!/usr/bin/env python

import logging
from systemd.journal import JournalHandler

log = logging.getLogger('test')
log_fmt = logging.Formatter("%(levelname)s %(message)s")
log_ch = JournalHandler()
log_ch.setFormatter(log_fmt)
log.addHandler(log_ch)
log.setLevel(logging.DEBUG)
log.warning("warn")
log.info("info")
log.error("error")
log.debug("debug")

This gives your desired output in the log

Nov 24 01:16:50 localhost.localdomain app.py[11279]: WARNING warn
Nov 24 01:16:50 localhost.localdomain app.py[11279]: INFO info
Nov 24 01:16:50 localhost.localdomain app.py[11279]: ERROR error
Nov 24 01:16:50 localhost.localdomain app.py[11279]: DEBUG debug
martineg
  • 1,269
  • 13
  • 14
  • What is the difference between JournalHandler and SysLogHandler ? `/dev/log -> /run/systemd/journal/dev-log` – madzohan Aug 09 '17 at 10:48
  • The JournalHandler will send a log entry to the local systemd journal, while the SysLogHandler will send a log entry to a remote (or local) syslog server. – martineg Aug 10 '17 at 09:28