Skip to content

Commit 2394659

Browse files
committed
log user-agent to console access logs
* Taken from: https://groups.google.com/forum/#!topic/python-tornado/uomAkaY05cc * Update the standard access log to mimic Apache style. * Prefix application error logs with "[User-Agent: foo]".
1 parent eee24a6 commit 2394659

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

mfr/server/app.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import time
12
import signal
23
import asyncio
34
import logging
@@ -19,6 +20,7 @@
1920
from mfr.version import __version__
2021

2122
logger = logging.getLogger(__name__)
23+
access_logger = logging.getLogger('tornado.access')
2224

2325

2426
def sig_handler(sig, frame):
@@ -33,6 +35,16 @@ def stop_loop():
3335
io_loop.add_callback_from_signal(stop_loop)
3436

3537

38+
def almost_apache_style_log(handler):
39+
'''without status code and body length'''
40+
req = handler.request
41+
access_logger.info('%s - - [%s +0800] "%s %s %s" - - "%s" "%s"' %
42+
(req.remote_ip, time.strftime("%d/%b/%Y:%X"), req.method,
43+
req.uri,
44+
req.version, getattr(req, 'referer', '-'),
45+
req.headers['User-Agent']))
46+
47+
3648
def make_app(debug):
3749
app = tornado.web.Application(
3850
[
@@ -45,6 +57,7 @@ def make_app(debug):
4557
(r'/status', StatusHandler),
4658
],
4759
debug=debug,
60+
log_function=almost_apache_style_log,
4861
)
4962
app.sentry_client = AsyncSentryClient(settings.SENTRY_DSN, release=__version__)
5063
return app

mfr/server/handlers/core.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -203,8 +203,10 @@ def log_exception(self, typ, value, tb):
203203
list(value.args))
204204
tornado.web.gen_log.warning(format, *args)
205205
else:
206-
tornado.web.app_log.error("Uncaught exception %s\n", self._request_summary(),
207-
exc_info=(typ, value, tb))
206+
tornado.web.app_log.error("[User-Agent: %s] Uncaught exception %s\n",
207+
self.request.headers.get('User-Agent', '*none found*'),
208+
self._request_summary(),
209+
exc_info=(typ, value, tb))
208210

209211
def on_finish(self):
210212
if self.request.method not in self.ALLOWED_METHODS:

0 commit comments

Comments
 (0)