Python重定向日志

Python重定向日志,python,tornado,Python,Tornado,我正在运行一个web服务器tornado,我正在尝试使用以下命令将所有日志输出重定向到一个文件。但是我在文件中没有看到输出 /usr/bin/python -u index.py 2>&1 >> /tmp/tornado.log 我将-u选项传递给python解释器。我仍然没有看到任何输出记录到我的日志文件中 但是,当我执行以下操作时,我会在stdout上看到输出 /usr/bin/python index.py Tornado使用内置的日志模块。您可以轻松地将文件

我正在运行一个web服务器tornado,我正在尝试使用以下命令将所有日志输出重定向到一个文件。但是我在文件中没有看到输出

/usr/bin/python -u index.py 2>&1 >> /tmp/tornado.log
我将-u选项传递给python解释器。我仍然没有看到任何输出记录到我的日志文件中

但是,当我执行以下操作时,我会在stdout上看到输出

/usr/bin/python index.py

Tornado使用内置的日志模块。您可以轻松地将文件处理程序附加到根记录器,并将其级别设置为
NOTSET
,以便它记录所有内容,或者,如果您想进行筛选,可以将其设置为其他级别

参考文件:

使用Tornado的日志记录的示例:

import logging
# the root logger is created upon the first import of the logging module

# create a file handler to add to the root logger
filehandler = logging.FileHandler(
    filename = 'test.log', 
    mode = 'a', 
    encoding = None, 
    delay = False
)

# set the file handler's level to your desired logging level, e.g. INFO
filehandler.setLevel(logging.INFO)

# create a formatter for the file handler
formatter = logging.Formatter('%(asctime)s.%(msecs)d  [%(name)s](%(process)d): %(levelname)s: %(message)s')

# add filters if you want your handler to only handle events from specific loggers 
# e.g. "main.sub.classb" or something like that. I'll leave this commented out.
# filehandler.addFilter(logging.Filter(name='root.child'))

# set the root logger's level to be at most as high as your handler's
if logging.root.level > filehandler.level:
    logging.root.setLevel = filehandler.level

# finally, add the handler to the root. after you do this, the root logger will write
# records to file.
logging.root.addHandler(filehandler)

通常情况下,我实际上希望抑制tornado的日志记录程序(因为我有自己的日志记录程序,并捕获它们的异常,它们最终会污染我的日志),而这正是在您的文件处理程序上添加过滤器非常方便的地方。

在您的应用程序中将文件处理程序附加到根日志记录程序会起作用吗?