Python 如何将龙卷风日志存储到文件中?
我一直面临这样的问题:如果API连续30分钟不被访问,我的服务器就会抛出500个错误。为了检查问题,我需要跟踪每个API请求。我在烧瓶前用龙卷风。这是我目前的代码:Python 如何将龙卷风日志存储到文件中?,python,flask,tornado,Python,Flask,Tornado,我一直面临这样的问题:如果API连续30分钟不被访问,我的服务器就会抛出500个错误。为了检查问题,我需要跟踪每个API请求。我在烧瓶前用龙卷风。这是我目前的代码: import tornado.httpserver import tornado.ioloop import tornado.web from flasky import app from tornado.wsgi import WSGIContainer from tornado.ioloop import IOLoop from
import tornado.httpserver
import tornado.ioloop
import tornado.web
from flasky import app
from tornado.wsgi import WSGIContainer
from tornado.ioloop import IOLoop
from tornado.web import FallbackHandler
from tornado.log import enable_pretty_logging
enable_pretty_logging()
tr = WSGIContainer(app)
application = tornado.web.Application([
(r".*", FallbackHandler, dict(fallback=tr)),
])
if __name__ == '__main__':
application.listen(5000)
IOLoop.instance().start()
将日志存储到某个文件中最有效的方法是什么
我尝试过这样做,但它仅在进程以0退出时起作用:
import sys
import time
timestr = time.strftime("%Y%m%d-%H%M%S")
filename = "C:/Source/logs/" + timestr + ".log"
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
self.log = open(filename, "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
pass
sys.stdout = Logger()
您已经使用了这是好的,如果您可能会注意到文档中说您可以传递一个记录器。那么什么是记录器呢?事实证明,Python对通过内置模块记录操作具有非常广泛的支持(文档中也提到了这一点)。通常,您需要设置写入特定文件的处理程序,您可以通过
handler = logging.FileHandler(log_file_filename)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.info('foo')
这将把所有信息级别(或更高级别)的条目记录到文件中。这些记录器可以通过logging.getLogger
功能收集,您可以通过
access_log = logging.getLogger("tornado.access")
app_log = logging.getLogger("tornado.application")
gen_log = logging.getLogger("tornado.general")
只需将处理程序附加到正在生成要记录到文件中的消息的记录器。如果是tornado.application
生成您想要查看的消息
handler = logging.FileHandler(log_file_filename)
app_log = logging.getLogger("tornado.application")
enable_pretty_logging()
app_log.addHandler(handler)
或者您也可以使用内置的tornado选项来启用此功能
tornado.options.options['log_file_prefix'].set(log_file_prefix)
tornado.options.parse_command_line()
非常感谢!内置龙卷风选项完全有效。