webpy日志记录以分隔日志文件

时间:2017-03-19 09:57:19

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

我正在使用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

我在第二个curl命令

之后的subtype2.log中得到以下内容
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"

1 个答案:

答案 0 :(得分:1)

您的代码中存在两个问题。

你说,

  

我在subtype1.log和subtype2.log

中获得相同的日志记录信息

原因是您需要创建两个独立的,完全不同的日志记录对象。您可以通过传递所需名称logging.getLogger()来完成此操作。

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

  1. 多次调用时,日志会重复。 (你没有注意到它,但你的代码中存在这个问题。)
  2. 原因是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