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)

  • 相关阅读:
    运行jar包读取外部配置文件
    DES加密
    BlockingQueue
    文件锁
    Hive 的 排序
    linux下date命令实现时间戳与日期的转换
    bcov进行覆盖率统计
    对c++服务端进行覆盖率统计
    github基础命令
    gcc编译参数-fPIC问题 `a local symbol' can not be used when making a shared object;
  • 原文地址:https://www.cnblogs.com/flowjacky/p/4953758.html
Copyright © 2011-2022 走看看