需求
终端运行python程序使其后台运行,并将屏幕的输出定向到日志,关闭终端不受影响
方案
测试程序
用于输出日志和打印到控制台。
#-*- coding: utf-8 -*-
import logging
import time
from logging.handlers import RotatingFileHandler
def func():
init_log()
while True:
print("output to the console")
logging.debug("output the debug log")
logging.info("output the info log")
time.sleep(3);
def init_log():
logging.getLogger().setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
console.setFormatter(formatter)
logging.getLogger().addHandler(console)
# add log ratate
Rthandler = RotatingFileHandler("backend_run.log", maxBytes=10 * 1024 * 1024, backupCount=100,
encoding="gbk")
Rthandler.setLevel(logging.INFO)
# formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
Rthandler.setFormatter(formatter)
logging.getLogger().addHandler(Rthandler)
if __name__ == '__main__':
func()
终端运行程序
nohup python -u main.py > main.log 2>&1 &
终端返回进程id
[1] 9208
跟踪日志变化
tail -f main.log
终止程序
ps -ef | grep python
kill -9 9208
OK.