python - logging response content length using bottle and cherrypy -
i using bottle cherrypy (which provides wsgi) web application. cherrypy not log web-access in setup. currently, almost logging using bottle's hook plug-in, so:
import bottle bottle import route, static_file, get, post, error, request, template, redirect, response, hook @hook('after_request') def log_after_request(): try: length = response.content_length except: try: length = len(response.body) except: length = '???' print '{ip} - - [{time}] "{method} {uri} {protocol}" {status} {length}'.format( ip=request.environ.get('remote_addr'), time=datetime.datetime.now().strftime('%y-%m-%d %h:%m:%s'), method=request.environ.get('request_method'), uri=request.environ.get('request_uri'), protocol=request.environ.get('server_protocol'), status=response.status_code, length=length, ) @route('/index.html') def index_handler(): return '<h1>hello, world!</h1>' app = bottle.default_app() bottle.run(host='0.0.0.0', port='80', app=app, server='cherrypy', request_queue_size=300, debug=true)
this provides log entries stdout, so:
192.168.1.1 - - [2013-07-23 17:04:04] "get /index.html http/1.1" 200 0
this correct, except content-length 0. appears bottle unaware of content-length returned cherrypy. correct assessment, , more importantly, there way retrieve it, can log it?
i open better ways obtain access logging using bottle , cherrypy.
thanks!
i can think of several approaches, here's 1 think best: use middleware app log requests.
here's complete example based on code in question. (i haven't changed log_after_request
; of action in accesslogmiddleware.__call__
.)
import datetime import bottle bottle import route, static_file, get, post, error, request, template, redirect, response, hook # unchanged op @route('/index.html') def index_handler(): return '<h1>hello, world!</h1>' # unchanged op def log_after_request(): try: length = response.content_length except: try: length = len(response.body) except: length = '???' print 'mylog:', '{ip} - - [{time}] "{method} {uri} {protocol}" {status} {length}'.format( ip=request.environ.get('remote_addr'), time=datetime.datetime.now().strftime('%y-%m-%d %h:%m:%s'), method=request.environ.get('request_method'), uri=request.environ.get('request_uri'), protocol=request.environ.get('server_protocol'), status=response.status_code, length=length, ) # code i've added begins here class accesslogmiddleware(object): def __init__(self, app): self.app = app def __call__(self, e, h): # call bottle , store return value ret_val = self.app(e, h) # log request log_after_request() # return bottle's return value return ret_val app = bottle.app() logged_app = accesslogmiddleware(app) bottle.run(host='0.0.0.0', port='8000', app=logged_app)
that should trick; if not, let me know , i'll help.
Comments
Post a Comment