How to redirect output to web.py

About web.py How to redirect output to another output as a log file or completely get rid of it?

+5
source share
5 answers

Console output is printsent 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 method write().

class MyOutputStream(object):

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

import sys
sys.stdout = MyOutputStream()

print("Test")  # Output is ignored

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

sys.stdout = sys.__stdout__  # Restore stdout
+2
source

http://webpy.org/cookbook/logging, / . , ( ) WsgiLogging, init, .

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

'logformat' FileLogger, .

, /, web.py. (LogMiddleware httpserver.py) . FileLogger , LogMiddleware.

, , stdout stderr /dev/null;

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

, !

RDP

+4

:

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

Python .

, , . , .

0

, , , web.py

, HTTPServer .

Update:

Another solution would be to directly modify the web.py code and redirect the print to httpserver.pythe file, as recommended here .

0
source

to get rid of him

web.config.debug = False still did not help. Some result was still implemented.

The output of the comment line in the file: C: \ python27 \ Lib \ site-packages \ Web \ httpserver.py

line:

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

All Articles