Last active
January 5, 2024 14:07
-
-
Save mc3k/0d0f19d6a92387d2b564cbaec3cdcc54 to your computer and use it in GitHub Desktop.
Logging example for Python Daemon
This file contains 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
#!/usr/bin/env python | |
# visit https://www.childs.be/blog/post/how-to-run-a-python-script-as-a-service-in-background-as-a-daemon for instructions | |
# uses https://raw.githubusercontent.com/metachris/python-posix-daemon/master/src/daemon2x.py | |
import time, sys, logging | |
from daemon2x import Daemon | |
# Logging | |
logging.basicConfig( filename='/var/log/daemon-example.log', | |
filemode='a', | |
format='[%(asctime)s] %(message)s', | |
datefmt='%Y/%d/%m %H:%M:%S', | |
level=logging.INFO) | |
class MyDaemon(Daemon): | |
def run(self): | |
logging.info('--------------') | |
logging.info('Daemon Started') | |
while True: | |
logging.info(time.strftime("%I:%M:%S %p")) | |
time.sleep(2) | |
logging.info('Daemon Ended') | |
if __name__ == "__main__": | |
daemonx = MyDaemon('/tmp/daemon-example.pid') | |
if len(sys.argv) == 2: | |
if 'start' == sys.argv[1]: | |
daemonx.start() | |
elif 'stop' == sys.argv[1]: | |
logging.info('Daemon Stopped') | |
daemonx.stop() | |
elif 'restart' == sys.argv[1]: | |
logging.info('Daemon restarting') | |
daemonx.restart() | |
else: | |
print("Unknown command") | |
sys.exit(2) | |
sys.exit(0) | |
else: | |
print("usage: %s start|stop|restart" % sys.argv[0]) | |
sys.exit(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment