Tornado替代了服务器上的自定义记录器(不在本地计算机上)



我有一个龙卷风应用程序和一个自定义记录器方法。我构建和使用自定义记录器的代码如下:

def create_logger():
"""
This function creates the logger functionality to be used throughout the Python application
:return: bool - true if successful
"""
# Configuring the logger
filename = "PythonLogger.log"
# Change the current working directory to the logs folder, so that the logs files is written in it.
os.chdir(os.path.normpath(os.path.normpath(os.path.dirname(os.path.abspath(__file__)) + os.sep + os.pardir + os.sep + os.pardir + os.sep + 'logs')))
# Create the logs file
logging.basicConfig(filename=filename,  format='%(asctime)s %(message)s', filemode='w')
# Creating the logger
logger = logging.getLogger()
# Setting the threshold of logger to DEBUG
logger.setLevel(logging.NOTSET)
logger.log(0, 'El logger está inicializado')
return True
def log_info_message(msg):
"""
Utility for message logging with code 20
:param msg:
:return:
"""
return logging.getLogger().log(20, msg)

在代码中,我初始化了记录器,并在Tornado应用程序初始化之前向其写入了一条消息:

if __name__ == '__main__':

# Logger initialization
create_logger()
# First log message
log_info_message('Initiating Python application')
# Starting Tornado
tornado.options.parse_command_line()
# Specifying what app exactly is being started
server = tornado.httpserver.HTTPServer(test.app)
server.listen(options.port)
try:
if 'Windows_NT' not in os.environ.values():
server.start(0)
tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
tornado.ioloop.IOLoop.instance().stop()

然后让我们假设我的HTTP请求获取方法如下(只有有趣的行):

class API(tornado.web.RequestHandler):
def get(self):
self.write('Get request    ')
logging.getLogger("tornado.access").log(20, 'Hola') 
logging.getLogger("tornado.application").log(20, '1')
logging.getLogger("tornado.general").log(20, '2')
log_info_message('Received a GET request at: ' + datetime.datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)"))

我看到的是本地测试和服务器测试之间的区别。

A) 在本地,我可以在第一个脚本运行时看到日志消息,并在我的日志文件和Tornado日志中看到请求的日志消息(初始化Tornado应用程序后)。

B) 在服务器上,当Get请求被接受时,我只看到第一条消息,而不是我的日志消息,当出现错误时,我也会看到Tornado的记录器,但甚至看不到Tornado记录器产生的消息。我想这意味着Tornado正在以某种方式重新初始化记录器,并使我和他的3个记录器写入其他文件(不知何故,这不会影响错误发生的时间??)。

我知道Tornado使用自己的3个日志记录功能,但不知何故,我也想使用我的,同时保留Tornado的日志记录功能并将它们全部写入同一文件。基本上在服务器上复制本地行为,当然,当发生错误时也会保留它。

我怎样才能做到这一点?

提前感谢!

附言:如果我给记录器添加一个名称,比如logging.getLogger('Example'),并将log_info_message函数更改为return logging.getLogger('Example').log(20, msg),Tornado的记录器将失败并引发错误。因此,该选项会破坏自己的记录器。。。

似乎唯一的问题是,在服务器端,toronto将要写入日志文件的日志消息的最小数量级别设置得更高(至少需要40个)。因此logging.getLogger().log(20, msg)不会写入日志文件,而logging.getLogger().log(40, msg)会写入。

我想知道为什么,所以如果有人知道的话,你的知识将非常受欢迎。不过,目前这个解决方案正在发挥作用。

tornado.log定义了可用于通过命令行自定义日志记录的选项(选中toronto.options),其中之一是定义所用日志级别的logging。您可能会在服务器上使用它,并将其设置为error

在调试日志记录时,我建议您创建一个RequestHandler,它将通过检查根记录器来记录或返回现有记录器的结构。当你看到这个结构时,就更容易理解为什么它会以这种方式工作。

相关内容

最新更新