【问题标题】:webpy logging to separate log fileswebpy 日志记录到单独的日志文件
【发布时间】:2017-03-19 09:57:19
【问题描述】:

我正在使用 webpy 来托管一个带有 2 个子服务的简单 Web 服务。 我想使用 python 日志包将每个子服务的信息记录到不同的日志文件中。 下面展示了 test_logging.py(运行 webpy 的主要函数)和 test_classC.py(做后端服务的函数)。

# test_logging.py

import web
from test_classC import classC

urls = (
    '/nw1', 'nw1',
    '/nw2', 'nw2',
)

class nw1:
    cc = classC('subtype1')

    def POST(self):
        self.cc.logsomething()

class nw2:
    cc = classC('subtype2')

    def POST(self):
        self.cc.logsomething()

if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()

# test_classC.py

import logging

class classC:

    def __init__(self, subtype):
        self.nw_type = subtype
        logfile = subtype + '.log'

        self._log = logging.getLogger()
        self._log.setLevel(logging.INFO)
        handler = logging.FileHandler(logfile)
        self._log.addHandler(handler)


    def logsomething(self):
        self._log.info("This is network type: %s" %self.nw_type)

显然我没有正确编写日志记录。当我使用 curl 使用以下 web 命令进行测试时...

$ curl localhost:8081/nw1 --data-binary "hello"
$ curl localhost:8081/nw2 --data-binary "hello"

我在 subtype1.log 和 subtype2.log 中得到相同的日志信息。第一个 curl 命令生成前两行,第二个 curl 命令生成第三和第四行。

This is network type: subtype1
This is network type: subtype1
This is network type: subtype2
This is network type: subtype2

我怎样才能记录这样的信息

在第一个 curl 命令之后,我在 subtype1.log 中得到以下内容

This is network type: subtype1

我在 subtype2.log 第二个 curl 命令之后得到以下内容

This is network type: subtype2

[这是可选的,但我很好奇] 另外,由于这是一个 Web 服务,当两个用户并行访问同一个 Web 服务时,如何确保正确记录信息。例如。并行发送以下命令

$ curl localhost:8081/nw1 --data-binary "request_a_very_heavy_load_serv"
$ curl localhost:8081/nw1 --data-binary "request_a_very_heavy_load_serv"

【问题讨论】:

  • 这很奇怪。我现在正在尝试一个小时.. 嗯
  • 呸!! 2 小时后找到了问题的解决方法.. 检查我的答案。 :)

标签: python python-2.7 curl logging web.py


【解决方案1】:

您的代码中有两个问题。

你说,

我在 subtype1.log 和 subtype2.log 中得到相同的日志记录信息

原因是您需要创建两个独立的、完全不同的日志记录对象。您可以通过传递您想要的名称来使用logging.getLogger()

在你的情况下应该是self._log = logging.getLogger(self.logfile)

  1. 当您多次调用它们时,日志会重复。 (您没有注意到它,但您的代码中存在该问题。)

原因是logging.getLogger() 是一个单例。因此,每次您创建 Class C 的实例时,它都会向该实例添加另一个处理程序,这会导致日志重复。 所以我在添加处理程序之前检查了if not len(self._log.handlers):

所以你最终的test_classC.py如下,

# test_classC.py
import logging

class classC:

    def __init__(self, subtype):

        self.nw_type = subtype
        self.logfile = subtype + '.log'
        self._log = logging.getLogger(self.logfile)
        if not len(self._log.handlers):
            self._log.setLevel(logging.INFO)
            self.handler = logging.FileHandler(self.logfile)
            self._log.addHandler(self.handler)

    def logsomething(self):
        self._log.info("This is network type: %s" %self.nw_type)

要测试并行请求,您可以使用jmeter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多