如何重定向 web.py 中的输出

发布于 2024-12-01 10:13:20 字数 50 浏览 2 评论 0原文

关于 web.py 如何将输出重定向到另一个输出目的地 像日志文件一样还是完全删除它?

About web.py How do I redirrect the output to another output destination
like a log file or get rid of it completely?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

节枝 2024-12-08 10:13:20

我必须修改 http://webpy.org/cookbook/logging 中的示例才能记录对文件的请求/响应事件。基本上,除了(根据链接的示例)传递重载 init 的 WsgiLogging 实例之外,还需要重载 call 函数。

class FileLog(WsgiLog):
  def __init__(self, application):
    WsgiLog.__init__(
        self,
        application,
        logformat = '[%(asctime)s][%(name)s][%(levelname)s]: %(message)s',
        debug = True,
        tofile = web.config.log_tofile,
        toprint =  False,
        file = web.config.log_file,
        loglevel = logging.DEBUG
        )

  def __call__(self, environ, start_response):
    def hstart_response(status, response_headers, *args):
      out = start_response(status, response_headers, *args)
      try:
        logline=environ["SERVER_PROTOCOL"]+" "+environ["REQUEST_METHOD"]+" "+environ["REQUEST_URI"]+" - "+status

      except err:
        logline="Could not log <%s> due to err <%s>" % (str(environ), err)

      self.logger.info(logline)

      return out

    return super(FileLog, self).__call__(environ, hstart_response)

web.config 变量在我的主函数中设置,

import sys
import os
import datetime, time
import optparse
import logging
from wsgilog import WsgiLog

if __name__ == "__main__":

   parser = optparse.OptionParser()


   parser.add_option("--logfile", dest="logfile",  default="",
              help="OPTIONAL send log messages to specified file instead of std out")

   (options, args) = parser.parse_args()

   #P Need to "eat" all of the passed in args because webpy will try to interpret them first
   sys.argv = []

   webpyapp = web.application(urls, locals())

   if hasattr(options, "logfile") and options.logfile != '':
     web.config.log_file = options.logfile
     web.config.log_toprint = False
     web.config.log_tofile = True
     webpyapp.run(FileLog)
   else:
     webpyapp.run()

这将记录请求事件和对指定文件的响应,如下所示

[Tue, 01 Apr 2014 17:40:56][wsgilog.log][INFO]: HTTP/1.1 OPTIONS /api/sessions/5399d05f41f0 - 200 OK
[Tue, 01 Apr 2014 17:40:56][wsgilog.log][INFO]: HTTP/1.1 GET /api/sessions/5399d05f41f0 - 200 OK
[Tue, 01 Apr 2014 17:40:56][wsgilog.log][INFO]: HTTP/1.1 GET /api/sessions/5399d05f41f0/tasks/ - 200 OK
[Tue, 01 Apr 2014 17:40:56][wsgilog.log][INFO]: HTTP/1.1 GET /api/sessions/5399d05f41f0/tasks//messages/?timestamp__gt=1396291350 - 200 OK

修改 FileLogger 中的“logformat”变量以更改文件中输出的格式化方式。

据我所知,没有办法抑制 web.py 框架生成的请求/响应消息的输出。它使用自己的类(httpserver.py 中的 LogMiddleware)来打印事件。 FileLogger 只是将自身添加到各种记录器中,它不会取代 LogMiddleware。

一旦您按照需要将日志记录到文件中,您就可以将 stdout 和 stderr 的输出重定向到 /dev/null ;

./yourapp.py > /dev/null 2> /dev/null

希望这有帮助,祝你好运!

rdp

I had to modify the example from http://webpy.org/cookbook/logging to be able to log the request / response events to a file. Basically, in addition to (per the linked example) passing an instance of WsgiLogging that overloads init, the call function also needs to be overloaded.

class FileLog(WsgiLog):
  def __init__(self, application):
    WsgiLog.__init__(
        self,
        application,
        logformat = '[%(asctime)s][%(name)s][%(levelname)s]: %(message)s',
        debug = True,
        tofile = web.config.log_tofile,
        toprint =  False,
        file = web.config.log_file,
        loglevel = logging.DEBUG
        )

  def __call__(self, environ, start_response):
    def hstart_response(status, response_headers, *args):
      out = start_response(status, response_headers, *args)
      try:
        logline=environ["SERVER_PROTOCOL"]+" "+environ["REQUEST_METHOD"]+" "+environ["REQUEST_URI"]+" - "+status

      except err:
        logline="Could not log <%s> due to err <%s>" % (str(environ), err)

      self.logger.info(logline)

      return out

    return super(FileLog, self).__call__(environ, hstart_response)

The web.config variables are set up in my main function

import sys
import os
import datetime, time
import optparse
import logging
from wsgilog import WsgiLog

if __name__ == "__main__":

   parser = optparse.OptionParser()


   parser.add_option("--logfile", dest="logfile",  default="",
              help="OPTIONAL send log messages to specified file instead of std out")

   (options, args) = parser.parse_args()

   #P Need to "eat" all of the passed in args because webpy will try to interpret them first
   sys.argv = []

   webpyapp = web.application(urls, locals())

   if hasattr(options, "logfile") and options.logfile != '':
     web.config.log_file = options.logfile
     web.config.log_toprint = False
     web.config.log_tofile = True
     webpyapp.run(FileLog)
   else:
     webpyapp.run()

This will log the request events and the response to the specified file, like this

[Tue, 01 Apr 2014 17:40:56][wsgilog.log][INFO]: HTTP/1.1 OPTIONS /api/sessions/5399d05f41f0 - 200 OK
[Tue, 01 Apr 2014 17:40:56][wsgilog.log][INFO]: HTTP/1.1 GET /api/sessions/5399d05f41f0 - 200 OK
[Tue, 01 Apr 2014 17:40:56][wsgilog.log][INFO]: HTTP/1.1 GET /api/sessions/5399d05f41f0/tasks/ - 200 OK
[Tue, 01 Apr 2014 17:40:56][wsgilog.log][INFO]: HTTP/1.1 GET /api/sessions/5399d05f41f0/tasks//messages/?timestamp__gt=1396291350 - 200 OK

Modify the 'logformat' variable in FileLogger to change the way the output is formated in the file.

As far as I can tell, there is not a way to supress the output of the the request / response messages that are generated by the web.py framework. It uses its own class (LogMiddleware in httpserver.py) to print out events. The FileLogger just adds itself to the various loggers, it does not replace LogMiddleware.

Once you have logging going to the file as you want, you could just redirect the output of stdout and stderr to /dev/null;

./yourapp.py > /dev/null 2> /dev/null

Hope this helps and good luck!

rdp

月亮是我掰弯的 2024-12-08 10:13:20

print 的控制台输出被发送到 sys.stdout。如果需要,您可以用打开的文件或您自己的类似文件的对象替换该流。唯一的要求是您的自定义对象具有 write() 方法。

class MyOutputStream(object):

    def write(self, data):
        pass   # Ignore output

import sys
sys.stdout = MyOutputStream()

print("Test")  # Output is ignored

如果要访问或恢复原始输出流,请使用 sys.__stdout__ 。

sys.stdout = sys.__stdout__  # Restore stdout

Console output by print is sent to sys.stdout. You can replace this stream with an open file or your own file-like object if you want. The only requirement is that your custom object has a write() method.

class MyOutputStream(object):

    def write(self, data):
        pass   # Ignore output

import sys
sys.stdout = MyOutputStream()

print("Test")  # Output is ignored

If you want to access or restore the original output stream, use sys.__stdout__.

sys.stdout = sys.__stdout__  # Restore stdout
姐不稀罕 2024-12-08 10:13:20

你可以像这样打印到文件:

 file = open("/tmp/test.txt", "wt")
 print >> file, "Foobar"

Python还为日志功能提供了logging模块。

然而,问题的质量给解释你想要输出的内容和原因留下了太多的空间,因此不可能给出一个好的答案。请尝试编辑问题以获取更多详细信息。

You can print to a file like this:

 file = open("/tmp/test.txt", "wt")
 print >> file, "Foobar"

Python also provides logging module for log functions.

However the quality of the question leaves too much for interpretation what you are trying to output and why, thus giving a good answer is impossible. Please try to edit the question for more details.

听风吹 2024-12-08 10:13:20

虽然这是一个旧线程,但遇到它的人可能会对这个来自 web.py Cookbook 的解决方案

感兴趣基本上解释了如何控制默认 HTTPServer 的日志记录。

更新:

另一种解决方案是直接更改 web.py 的代码并将 httpserver.py 中的打印重定向到文件,如推荐的 此处

Although it's an old thread, people running into it might be interested in this solution from the web.py cookbook

It basically explains how to control logging for a default HTTPServer.

Update:

Another solution would be directly changing web.py's code and redirect the print in httpserver.py to a file, like recommended here.

情场扛把子 2024-12-08 10:13:20

摆脱它

web.config.debug = False 仍然没有帮助。一些输出仍然完成。

注释掉文件中的行:
C:\Python27\Lib\site-packages\web\httpserver.py

行:

print >> outfile, utils.safestr(msg) ->
#print >> outfile, utils.safestr(msg)

to get rid of it

web.config.debug = False still did not helped. Some output still was done.

Comment out line in file:
C:\Python27\Lib\site-packages\web\httpserver.py

line:

print >> outfile, utils.safestr(msg) ->
#print >> outfile, utils.safestr(msg)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文