【问题标题】:Tornado substituting custom logger on server (not on local computer)Tornado 替换服务器上的自定义记录器(不在本地计算机上)
【发布时间】: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


【解决方案1】:

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

我想了解原因,因此如果有人知道,欢迎您提供知识。不过,目前该解决方案正在发挥作用。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-15
      • 2010-11-05
      • 2011-02-15
      • 1970-01-01
      • 2022-06-20
      • 2011-04-06
      • 2014-06-26
      • 1970-01-01
      相关资源
      最近更新 更多