服务器端是nginx + uwsgi + flask
报错后,网上搜到可能是print语句引起,但是检查代码,并未发现print语句
开启logger:
import logging logging.basicConfig(filename='logger.log', format='%(asctime)s - %(levelname)s - %(message)s',level=logging.INFO) logger = logging.getLogger(__name__) #定义一次就可以,其他地方需要调用logger,只需要直接使用logger就行了 logger.setLevel(level=logging.INFO) #定义过滤级别 filehandler = logging.FileHandler("log.txt") # Handler用于将日志记录发送至合适的目的地,如文件、终端等 filehandler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') filehandler.setFormatter(formatter) console = logging.StreamHandler() #日志信息显示在终端terminal console.setLevel(logging.INFO) console.setFormatter(formatter) logger.addHandler(filehandler) logger.addHandler(console) logger.info("Start log") logger.debug("Do something") logger.warning("Something fail.") logger.info("Finish")
在产生异常的模块上:
try: ........ except Exception as e: logger.exception(e)
最后发现是该模块开启了多进程,多进程有个模块popen_fork.py中存在如下代码:
class Popen(object): method = 'fork' def __init__(self, process_obj): try: sys.stdout.flush() except (AttributeError, ValueError): pass try: sys.stderr.flush() except (AttributeError, ValueError): # pass self.returncode = None self._launch(process_obj)
是其中的sys.stdout.flush()和sys.stderr.flush()引起的,将涉及8行代码注释掉后,问题解决