I can think of several approaches, but here's the one I think is best: use a middleware app to log the requests.
Here's a complete example based on the code in your question. (I haven't changed log_after_request
; most of the action is in 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)
That should do the trick; if not, let me know and I'll help.