【发布时间】: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