zoukankan      html  css  js  c++  java
  • 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)

  • 相关阅读:
    MongoDB在windows服务器安装部署及远程连接MongoDB
    react 常用组件
    react component 语法报错解决
    yarn install node-sass(gulp-sass) 安装失败解决方案
    eslint 规则中文注释
    react jsx 代码格式化
    vue sublime 工欲善其事,必先利其器
    jenkins 配置
    nodejs 使用 superagent 与 cheerio 完成简单爬虫
    jQuery DOM对象区别与联系
  • 原文地址:https://www.cnblogs.com/flowjacky/p/4953758.html
Copyright © 2011-2022 走看看