Created
February 5, 2018 13:39
-
-
Save trstringer/e23f2fd3102f118fbf1a6857aacf74ed to your computer and use it in GitHub Desktop.
Python logging to systemd
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import random | |
import time | |
from systemd.journal import JournaldLogHandler | |
# get an instance of the logger object this module will use | |
logger = logging.getLogger(__name__) | |
# instantiate the JournaldLogHandler to hook into systemd | |
journald_handler = JournaldLogHandler() | |
# set a formatter to include the level name | |
journald_handler.setFormatter(logging.Formatter( | |
'[%(levelname)s] %(message)s' | |
)) | |
# add the journald handler to the current logger | |
logger.addHandler(journald_handler) | |
# optionally set the logging level | |
logger.setLevel(logging.DEBUG) | |
if __name__ == '__main__': | |
while True: | |
# log a sample event | |
logger.info( | |
'test log event to systemd! Random number: %s', | |
random.randint(0, 10) | |
) | |
# sleep for some time to not saturate the journal | |
time.sleep(5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment