Tre*_*vor 3 python logging cherrypy content-length bottle
我正在为 web 应用程序使用带有cherrypy(它提供 WSGI)的瓶子。CherryPy 在此设置中不记录 Web 访问。目前,我几乎正在使用 Bottle 的hook 插件记录所有内容,如下所示:
import bottle
from 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)
Run Code Online (Sandbox Code Playgroud)
这会向 STDOUT 提供日志条目,如下所示:
192.168.1.1 - - [2013-07-23 17:04:04] "GET /index.html HTTP/1.1" 200 0
Run Code Online (Sandbox Code Playgroud)
这几乎是正确的,除了内容长度始终为 0。 瓶子似乎不知道cherrypy 返回的内容长度。这是一个正确的评估,更重要的是,有没有办法检索它,以便我可以记录它?
我对使用 Bottle 和cherrypy 获取访问日志的更好方法持开放态度。
谢谢!
我可以想到几种方法,但这是我认为最好的方法:使用中间件应用程序来记录请求。
这是基于您问题中的代码的完整示例。(我没有改变log_after_request;大部分动作都在AccessLogMiddleware.__call__.)
import datetime
import bottle
from bottle import route, static_file, get, post, error, request, template, redirect, response, hook
# unchanged from OP
@route('/index.html')
def index_handler():
return '<h1>Hello, world!</h1>'
# unchanged from 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 and store the return value
ret_val = self.app(e, h)
# log the 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)
Run Code Online (Sandbox Code Playgroud)
这应该够了吧; 如果没有,请告诉我,我会提供帮助。