python to be linux daemon
所需第三方库:python-daemon[https://pypi.python.org/pypi/python-daemon/]
使用方式:
python linux_service.py start/stop/restart
from mythings import start from daemon import runner import os import logging import inspect class App: def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' self.pidfile_path = '/tmp/foo.pid' self.pidfile_timeout = 5 self.status = {'alive': True} this_file = inspect.getfile(inspect.currentframe()) current_path = os.path.abspath(os.path.dirname(this_file)) self.logfile = os.path.join(current_path, 'service.log') def _getLogger(self): logger = logging.getLogger('[My Service]') logger.setLevel(logging.DEBUG) fh = logging.FileHandler(self.logfile) fh.setLevel(logging.DEBUG) #ch = logging.StreamHandler() #ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') fh.setFormatter(formatter) #ch.setFormatter(formatter) logger.addHandler(fh) #logger.addHandler(ch) logger.info('init logger...') return logger def run(self): self.logger = self._getLogger() self.logger.info('linux svc do run...') start(self.status, self.logger) app = App() daemon_runner = runner.DaemonRunner(app) daemon_runner.do_action()
备注:
日志级别:UNSET < DEBUG < INFO < WARNNING < ERROR<CRITICAL
当ch.setLevel(logging.DEBUG)时,可以打印出级别大于等于DEBUG的日志(包括DEBUG,INFO ,WARNNING , ERROR,CRITICAL)