【发布时间】:2021-07-25 03:44:49
【问题描述】:
我有一个龙卷风应用程序和一个自定义记录器方法。我构建和使用自定义记录器的代码如下:
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请求的get方法如下(仅有趣的行):
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 的那些并将它们全部写入同一个文件。基本上是在服务器上重现该本地行为,但在发生某些错误时也会保留它,当然。
我怎样才能做到这一点?
提前致谢!
P.S.:如果我给记录器添加一个名称,比如说logging.getLogger('Example') 并将 log_info_message 函数更改为return logging.getLogger('Example').log(20, msg),Tornado 的记录器将失败并引发错误。所以这个选项会破坏它自己的记录器......
【问题讨论】:
-
您的代码顶部有
import tornado,对吗?初始化日志记录的第一个模块开始发号施令。如果您想要控制,请在导入之前创建您的记录器。 -
不幸的是,这只会使代码在服务器上失败,尽管它在本地机器上工作正常
标签: python logging server tornado