Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I redirrect the output in web.py

Tags:

python

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?

like image 232
Cletrix Avatar asked Aug 25 '11 15:08

Cletrix


1 Answers

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

like image 85
RDP Avatar answered Oct 12 '22 10:10

RDP