Skip to main content
 首页 » 编程设计

python之webpy 记录到单独的日志文件

2025年02月15日6JeffreyZhao

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

请您参考如下方法:

您的代码中有两个问题。

你说,

I get the same logging information in subtype1.log and 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