我试图在python中创建一个带有日志到文件选项的守护进程服务。如果我将pidfile参数添加到daemon。DaemonContext构造函数,logger不记录任何消息到logger.log文件。但是如果我去掉这个参数,一切都会正常工作。运行时没有任何错误。有人知道为什么pidfile参数在守护进程。DaemonContext禁用日志消息?怎么解呢?
任何帮助将不胜感激。由于
import signal
import daemon
import lockfile
import logging
import logging.handlers
def run():
logger = logging.getLogger("DaemonLog")
logger.setLevel(logging.INFO)
handler = logging.FileHandler('logger.log')
handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
logger.addHandler(handler)
daemon_context = daemon.DaemonContext(
working_directory='/opt/myDaemon',
umask=0o002,
pidfile=lockfile.FileLock('/var/run/myDaemon.pid'),
files_preserve=[handler.stream]
)
daemon_context.signal_map = {
signal.SIGTERM: terminate_collector,
signal.SIGHUP: terminate_collector,
signal.SIGABRT: terminate_collector
}
with daemon_context as context:
while True:
logger.info("log")
func()
time.sleep(PARAM_SLEEP)
if __name__ == "__main__":
run()
我成功解决了这个问题。问题是没有使用
命令创建pidfile。pidfile=lockfile.FileLock('/var/run/myDaemon.pid')
解决方案是使用daemon。Pidfile模块,而不是lockfile模块:
pidfile=daemon.pidfile.PIDLockFile('/var/run/myDaemon.pid')
完整代码解决方案:
import signal
import daemon
import daemon.pidfile
import lockfile
import logging
import logging.handlers
def run():
logger = logging.getLogger("DaemonLog")
logger.setLevel(logging.INFO)
handler = logging.FileHandler('logger.log')
handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
logger.addHandler(handler)
daemon_context = daemon.DaemonContext(
working_directory='/opt/myDaemon',
umask=0o002,
pidfile=daemon.pidfile.PIDLockFile('/var/run/myDaemon.pid'),
files_preserve=[handler.stream]
)
daemon_context.signal_map = {
signal.SIGTERM: terminate_collector,
signal.SIGHUP: terminate_collector,
signal.SIGABRT: terminate_collector
}
with daemon_context as context:
while True:
logger.info("log")
func()
time.sleep(PARAM_SLEEP)
if __name__ == "__main__":
run()