如何将龙卷风日志存储到文件中?

2024-06-25 23:17:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直面临这样的问题:如果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 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()

Tags: fromimportselflogapiwebappmessage
1条回答
网友
1楼 · 发布于 2024-06-25 23:17:56

您已经使用了^{}这很好,如果您可能注意到文档中说您可以传入一个记录器。那么什么是记录器?结果表明,Python对通过内置的^{}模块记录操作有非常广泛的支持(文档中也提到了这一点)。通常,您需要设置写入特定文件的处理程序,可以通过

handler = logging.FileHandler(log_file_filename)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.info('foo')

这将把所有信息级条目(或更高级别)记录到文件中。这些记录器可以通过logging.getLogger函数收集,您可以根据tornado文档通过

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.options.options['log_file_prefix'].set(log_file_prefix)
tornado.options.parse_command_line()

相关问题 更多 >