Python重定向日志

问题描述:

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

/usr/bin/python -u index.py 2>&1 >> /tmp/tornado.log 

我将-u选项传递给python解释器。我仍然没有看到任何输出记录到我的日志文件中。

但是,我看到,当我这样做stdout上输出

/usr/bin/python index.py 
+0

将文件处理程序附加到应用程序工作中的根记录器中? – 2013-02-12 07:54:01

龙卷风使用内置的日志模块。您可以轻松地将文件处理程序附加到根记录器,并将其级别设置为NOTSET,以便记录所有内容或其他级别(如果要过滤)。

参考文档:logginglogging.handlers

例,与龙卷风的记录工作:

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) 

往往不是,我其实是想抑制龙卷风的记录器(因为我有我自己的,并吸引他们例外,并且它们最终会污染我的日志),这就是在文件处理程序中添加筛选器非常方便的地方。