Skip to content
This repository
Browse code

Switch from root logger to separate loggers.

Rather than using one logger per module, use three semantically-defined
loggers:  tornado.access, tornado.application, and tornado.general.
  • Loading branch information...
commit 9b944aa25c81322a222f23a10efb2e9311663ea8 1 parent 1881958
Ben Darnell authored
26  tornado/auth.py
@@ -50,7 +50,6 @@ def _on_auth(self, user):
50 50
 import binascii
51 51
 import hashlib
52 52
 import hmac
53  
-import logging
54 53
 import time
55 54
 import urllib
56 55
 import urlparse
@@ -59,6 +58,7 @@ def _on_auth(self, user):
59 58
 from tornado import httpclient
60 59
 from tornado import escape
61 60
 from tornado.httputil import url_concat
  61
+from tornado.log import gen_log
62 62
 from tornado.util import bytes_type, b
63 63
 
64 64
 
@@ -150,7 +150,7 @@ def _openid_args(self, callback_uri, ax_attrs=[], oauth_scope=None):
150 150
 
151 151
     def _on_authentication_verified(self, callback, response):
152 152
         if response.error or b("is_valid:true") not in response.body:
153  
-            logging.warning("Invalid OpenID response: %s", response.error or
  153
+            gen_log.warning("Invalid OpenID response: %s", response.error or
154 154
                             response.body)
155 155
             callback(None)
156 156
             return
@@ -263,14 +263,14 @@ def get_authenticated_user(self, callback, http_client=None):
263 263
         oauth_verifier = self.get_argument("oauth_verifier", None)
264 264
         request_cookie = self.get_cookie("_oauth_request_token")
265 265
         if not request_cookie:
266  
-            logging.warning("Missing OAuth request token cookie")
  266
+            gen_log.warning("Missing OAuth request token cookie")
267 267
             callback(None)
268 268
             return
269 269
         self.clear_cookie("_oauth_request_token")
270 270
         cookie_key, cookie_secret = [base64.b64decode(escape.utf8(i)) for i in request_cookie.split("|")]
271 271
         if cookie_key != request_key:
272  
-            logging.info((cookie_key, request_key, request_cookie))
273  
-            logging.warning("Request token does not match cookie")
  272
+            gen_log.info((cookie_key, request_key, request_cookie))
  273
+            gen_log.warning("Request token does not match cookie")
274 274
             callback(None)
275 275
             return
276 276
         token = dict(key=cookie_key, secret=cookie_secret)
@@ -348,7 +348,7 @@ def _oauth_access_token_url(self, request_token):
348 348
 
349 349
     def _on_access_token(self, callback, response):
350 350
         if response.error:
351  
-            logging.warning("Could not fetch access token")
  351
+            gen_log.warning("Could not fetch access token")
352 352
             callback(None)
353 353
             return
354 354
 
@@ -547,7 +547,7 @@ def _on_post(self, new_entry):
547 547
 
548 548
     def _on_twitter_request(self, callback, response):
549 549
         if response.error:
550  
-            logging.warning("Error response %s fetching %s", response.error,
  550
+            gen_log.warning("Error response %s fetching %s", response.error,
551 551
                             response.request.url)
552 552
             callback(None)
553 553
             return
@@ -669,7 +669,7 @@ def _on_post(self, new_entry):
669 669
 
670 670
     def _on_friendfeed_request(self, callback, response):
671 671
         if response.error:
672  
-            logging.warning("Error response %s fetching %s", response.error,
  672
+            gen_log.warning("Error response %s fetching %s", response.error,
673 673
                             response.request.url)
674 674
             callback(None)
675 675
             return
@@ -930,17 +930,17 @@ def _on_get_user_info(self, callback, session, users):
930 930
 
931 931
     def _parse_response(self, callback, response):
932 932
         if response.error:
933  
-            logging.warning("HTTP error from Facebook: %s", response.error)
  933
+            gen_log.warning("HTTP error from Facebook: %s", response.error)
934 934
             callback(None)
935 935
             return
936 936
         try:
937 937
             json = escape.json_decode(response.body)
938 938
         except Exception:
939  
-            logging.warning("Invalid JSON from Facebook: %r", response.body)
  939
+            gen_log.warning("Invalid JSON from Facebook: %r", response.body)
940 940
             callback(None)
941 941
             return
942 942
         if isinstance(json, dict) and json.get("error_code"):
943  
-            logging.warning("Facebook error: %d: %r", json["error_code"],
  943
+            gen_log.warning("Facebook error: %d: %r", json["error_code"],
944 944
                             json.get("error_msg"))
945 945
             callback(None)
946 946
             return
@@ -1007,7 +1007,7 @@ def _on_login(self, user):
1007 1007
     def _on_access_token(self, redirect_uri, client_id, client_secret,
1008 1008
                         callback, fields, response):
1009 1009
         if response.error:
1010  
-            logging.warning('Facebook auth error: %s' % str(response))
  1010
+            gen_log.warning('Facebook auth error: %s' % str(response))
1011 1011
             callback(None)
1012 1012
             return
1013 1013
 
@@ -1090,7 +1090,7 @@ def _on_post(self, new_entry):
1090 1090
 
1091 1091
     def _on_facebook_request(self, callback, response):
1092 1092
         if response.error:
1093  
-            logging.warning("Error response %s fetching %s", response.error,
  1093
+            gen_log.warning("Error response %s fetching %s", response.error,
1094 1094
                             response.request.url)
1095 1095
             callback(None)
1096 1096
             return
10  tornado/autoreload.py
@@ -67,7 +67,6 @@
67 67
         del sys.path[0]
68 68
 
69 69
 import functools
70  
-import logging
71 70
 import os
72 71
 import pkgutil
73 72
 import sys
@@ -75,6 +74,7 @@
75 74
 import subprocess
76 75
 
77 76
 from tornado import ioloop
  77
+from tornado.log import gen_log
78 78
 from tornado import process
79 79
 
80 80
 try:
@@ -177,7 +177,7 @@ def _check_file(modify_times, path):
177 177
         modify_times[path] = modified
178 178
         return
179 179
     if modify_times[path] != modified:
180  
-        logging.info("%s modified; restarting server", path)
  180
+        gen_log.info("%s modified; restarting server", path)
181 181
         _reload()
182 182
 
183 183
 
@@ -272,13 +272,13 @@ def main():
272 272
                 # module) will see the right things.
273 273
                 exec f.read() in globals(), globals()
274 274
     except SystemExit, e:
275  
-        logging.info("Script exited with status %s", e.code)
  275
+        gen_log.info("Script exited with status %s", e.code)
276 276
     except Exception, e:
277  
-        logging.warning("Script exited with uncaught exception", exc_info=True)
  277
+        gen_log.warning("Script exited with uncaught exception", exc_info=True)
278 278
         if isinstance(e, SyntaxError):
279 279
             watch(e.filename)
280 280
     else:
281  
-        logging.info("Script exited normally")
  281
+        gen_log.info("Script exited normally")
282 282
     # restore sys.argv so subsequent executions will include autoreload
283 283
     sys.argv = original_argv
284 284
 
15  tornado/curl_httpclient.py
@@ -27,6 +27,7 @@
27 27
 
28 28
 from tornado import httputil
29 29
 from tornado import ioloop
  30
+from tornado.log import gen_log
30 31
 from tornado import stack_context
31 32
 
32 33
 from tornado.escape import utf8
@@ -51,7 +52,7 @@ def initialize(self, io_loop=None, max_clients=10):
51 52
             # socket_action is found in pycurl since 7.18.2 (it's been
52 53
             # in libcurl longer than that but wasn't accessible to
53 54
             # python).
54  
-            logging.warning("socket_action method missing from pycurl; "
  55
+            gen_log.warning("socket_action method missing from pycurl; "
55 56
                             "falling back to socket_all. Upgrading "
56 57
                             "libcurl and pycurl will improve performance")
57 58
             self._socket_action = \
@@ -263,7 +264,7 @@ def __init__(self, errno, message):
263 264
 
264 265
 def _curl_create():
265 266
     curl = pycurl.Curl()
266  
-    if logging.getLogger().isEnabledFor(logging.DEBUG):
  267
+    if gen_log.isEnabledFor(logging.DEBUG):
267 268
         curl.setopt(pycurl.VERBOSE, 1)
268 269
         curl.setopt(pycurl.DEBUGFUNCTION, _curl_debug)
269 270
     return curl
@@ -386,11 +387,11 @@ def ioctl(cmd):
386 387
         userpwd = "%s:%s" % (request.auth_username, request.auth_password or '')
387 388
         curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
388 389
         curl.setopt(pycurl.USERPWD, utf8(userpwd))
389  
-        logging.debug("%s %s (username: %r)", request.method, request.url,
  390
+        gen_log.debug("%s %s (username: %r)", request.method, request.url,
390 391
                       request.auth_username)
391 392
     else:
392 393
         curl.unsetopt(pycurl.USERPWD)
393  
-        logging.debug("%s %s", request.method, request.url)
  394
+        gen_log.debug("%s %s", request.method, request.url)
394 395
 
395 396
     if request.client_cert is not None:
396 397
         curl.setopt(pycurl.SSLCERT, request.client_cert)
@@ -426,12 +427,12 @@ def _curl_header_callback(headers, header_line):
426 427
 def _curl_debug(debug_type, debug_msg):
427 428
     debug_types = ('I', '<', '>', '<', '>')
428 429
     if debug_type == 0:
429  
-        logging.debug('%s', debug_msg.strip())
  430
+        gen_log.debug('%s', debug_msg.strip())
430 431
     elif debug_type in (1, 2):
431 432
         for line in debug_msg.splitlines():
432  
-            logging.debug('%s %s', debug_types[debug_type], line)
  433
+            gen_log.debug('%s %s', debug_types[debug_type], line)
433 434
     elif debug_type == 4:
434  
-        logging.debug('%s %r', debug_types[debug_type], debug_msg)
  435
+        gen_log.debug('%s %r', debug_types[debug_type], debug_msg)
435 436
 
436 437
 if __name__ == "__main__":
437 438
     AsyncHTTPClient.configure(CurlAsyncHTTPClient)
7  tornado/database.py
@@ -20,9 +20,10 @@
20 20
 
21 21
 import copy
22 22
 import itertools
23  
-import logging
24 23
 import time
25 24
 
  25
+from tornado.log import gen_log
  26
+
26 27
 try:
27 28
     import MySQLdb.constants
28 29
     import MySQLdb.converters
@@ -83,7 +84,7 @@ def __init__(self, host, database, user=None, password=None,
83 84
         try:
84 85
             self.reconnect()
85 86
         except Exception:
86  
-            logging.error("Cannot connect to MySQL on %s", self.host,
  87
+            gen_log.error("Cannot connect to MySQL on %s", self.host,
87 88
                           exc_info=True)
88 89
 
89 90
     def __del__(self):
@@ -207,7 +208,7 @@ def _execute(self, cursor, query, parameters):
207 208
         try:
208 209
             return cursor.execute(query, parameters)
209 210
         except OperationalError:
210  
-            logging.error("Error connecting to MySQL on %s", self.host)
  211
+            gen_log.error("Error connecting to MySQL on %s", self.host)
211 212
             self.close()
212 213
             raise
213 214
 
4  tornado/httpserver.py
@@ -27,13 +27,13 @@ class except to start a server at the beginning of the process
27 27
 from __future__ import absolute_import, division, with_statement
28 28
 
29 29
 import Cookie
30  
-import logging
31 30
 import socket
32 31
 import time
33 32
 
34 33
 from tornado.escape import native_str, parse_qs_bytes
35 34
 from tornado import httputil
36 35
 from tornado import iostream
  36
+from tornado.log import gen_log
37 37
 from tornado.netutil import TCPServer
38 38
 from tornado import stack_context
39 39
 from tornado.util import b, bytes_type
@@ -267,7 +267,7 @@ def _on_headers(self, data):
267 267
 
268 268
             self.request_callback(self._request)
269 269
         except _BadRequestException, e:
270  
-            logging.info("Malformed HTTP request from %s: %s",
  270
+            gen_log.info("Malformed HTTP request from %s: %s",
271 271
                          self.address[0], e)
272 272
             self.close()
273 273
             return
12  tornado/httputil.py
@@ -18,11 +18,11 @@
18 18
 
19 19
 from __future__ import absolute_import, division, with_statement
20 20
 
21  
-import logging
22 21
 import urllib
23 22
 import re
24 23
 
25 24
 from tornado.escape import native_str, parse_qs_bytes, utf8
  25
+from tornado.log import gen_log
26 26
 from tornado.util import b, ObjectDict
27 27
 
28 28
 
@@ -228,7 +228,7 @@ def parse_body_arguments(content_type, body, arguments, files):
228 228
                 parse_multipart_form_data(utf8(v), body, arguments, files)
229 229
                 break
230 230
         else:
231  
-            logging.warning("Invalid multipart/form-data")
  231
+            gen_log.warning("Invalid multipart/form-data")
232 232
 
233 233
 
234 234
 def parse_multipart_form_data(boundary, data, arguments, files):
@@ -247,7 +247,7 @@ def parse_multipart_form_data(boundary, data, arguments, files):
247 247
         boundary = boundary[1:-1]
248 248
     final_boundary_index = data.rfind(b("--") + boundary + b("--"))
249 249
     if final_boundary_index == -1:
250  
-        logging.warning("Invalid multipart/form-data: no final boundary")
  250
+        gen_log.warning("Invalid multipart/form-data: no final boundary")
251 251
         return
252 252
     parts = data[:final_boundary_index].split(b("--") + boundary + b("\r\n"))
253 253
     for part in parts:
@@ -255,17 +255,17 @@ def parse_multipart_form_data(boundary, data, arguments, files):
255 255
             continue
256 256
         eoh = part.find(b("\r\n\r\n"))
257 257
         if eoh == -1:
258  
-            logging.warning("multipart/form-data missing headers")
  258
+            gen_log.warning("multipart/form-data missing headers")
259 259
             continue
260 260
         headers = HTTPHeaders.parse(part[:eoh].decode("utf-8"))
261 261
         disp_header = headers.get("Content-Disposition", "")
262 262
         disposition, disp_params = _parse_header(disp_header)
263 263
         if disposition != "form-data" or not part.endswith(b("\r\n")):
264  
-            logging.warning("Invalid multipart/form-data")
  264
+            gen_log.warning("Invalid multipart/form-data")
265 265
             continue
266 266
         value = part[eoh + 4:-2]
267 267
         if not disp_params.get("name"):
268  
-            logging.warning("multipart/form-data value missing name")
  268
+            gen_log.warning("multipart/form-data value missing name")
269 269
             continue
270 270
         name = disp_params["name"]
271 271
         if disp_params.get("filename"):
26  tornado/ioloop.py
@@ -32,13 +32,13 @@
32 32
 import errno
33 33
 import heapq
34 34
 import os
35  
-import logging
36 35
 import select
37 36
 import thread
38 37
 import threading
39 38
 import time
40 39
 import traceback
41 40
 
  41
+from tornado.log import app_log, gen_log
42 42
 from tornado import stack_context
43 43
 
44 44
 try:
@@ -191,7 +191,7 @@ def close(self, all_fds=False):
191 191
                 try:
192 192
                     os.close(fd)
193 193
                 except Exception:
194  
-                    logging.debug("error closing fd %s", fd, exc_info=True)
  194
+                    gen_log.debug("error closing fd %s", fd, exc_info=True)
195 195
         self._waker.close()
196 196
         self._impl.close()
197 197
 
@@ -211,7 +211,7 @@ def remove_handler(self, fd):
211 211
         try:
212 212
             self._impl.unregister(fd)
213 213
         except (OSError, IOError):
214  
-            logging.debug("Error deleting fd from IOLoop", exc_info=True)
  214
+            gen_log.debug("Error deleting fd from IOLoop", exc_info=True)
215 215
 
216 216
     def set_blocking_signal_threshold(self, seconds, action):
217 217
         """Sends a signal if the ioloop is blocked for more than s seconds.
@@ -225,8 +225,8 @@ def set_blocking_signal_threshold(self, seconds, action):
225 225
         too long.
226 226
         """
227 227
         if not hasattr(signal, "setitimer"):
228  
-            logging.error("set_blocking_signal_threshold requires a signal module "
229  
-                       "with the setitimer method")
  228
+            gen_log.error("set_blocking_signal_threshold requires a signal module "
  229
+                           "with the setitimer method")
230 230
             return
231 231
         self._blocking_signal_threshold = seconds
232 232
         if seconds is not None:
@@ -244,9 +244,9 @@ def log_stack(self, signal, frame):
244 244
 
245 245
         For use with set_blocking_signal_threshold.
246 246
         """
247  
-        logging.warning('IOLoop blocked for %f seconds in\n%s',
248  
-                        self._blocking_signal_threshold,
249  
-                        ''.join(traceback.format_stack(frame)))
  247
+        gen_log.warning('IOLoop blocked for %f seconds in\n%s',
  248
+                         self._blocking_signal_threshold,
  249
+                         ''.join(traceback.format_stack(frame)))
250 250
 
251 251
     def start(self):
252 252
         """Starts the I/O loop.
@@ -330,10 +330,10 @@ def start(self):
330 330
                         # Happens when the client closes the connection
331 331
                         pass
332 332
                     else:
333  
-                        logging.error("Exception in I/O handler for fd %s",
  333
+                        app_log.error("Exception in I/O handler for fd %s",
334 334
                                       fd, exc_info=True)
335 335
                 except Exception:
336  
-                    logging.error("Exception in I/O handler for fd %s",
  336
+                    app_log.error("Exception in I/O handler for fd %s",
337 337
                                   fd, exc_info=True)
338 338
         # reset the stopped flag so another start/stop pair can be issued
339 339
         self._stopped = False
@@ -432,7 +432,7 @@ def handle_callback_exception(self, callback):
432 432
         The exception itself is not passed explicitly, but is available
433 433
         in sys.exc_info.
434 434
         """
435  
-        logging.error("Exception in callback %r", callback, exc_info=True)
  435
+        app_log.error("Exception in callback %r", callback, exc_info=True)
436 436
 
437 437
 
438 438
 class _Timeout(object):
@@ -501,7 +501,7 @@ def _run(self):
501 501
         try:
502 502
             self.callback()
503 503
         except Exception:
504  
-            logging.error("Error in periodic callback", exc_info=True)
  504
+            app_log.error("Error in periodic callback", exc_info=True)
505 505
         self._schedule_next()
506 506
 
507 507
     def _schedule_next(self):
@@ -668,5 +668,5 @@ def poll(self, timeout):
668 668
         # All other systems
669 669
         import sys
670 670
         if "linux" in sys.platform:
671  
-            logging.warning("epoll module not found; using select()")
  671
+            gen_log.warning("epoll module not found; using select()")
672 672
         _poll = _Select
22  tornado/iostream.py
@@ -20,13 +20,13 @@
20 20
 
21 21
 import collections
22 22
 import errno
23  
-import logging
24 23
 import os
25 24
 import socket
26 25
 import sys
27 26
 import re
28 27
 
29 28
 from tornado import ioloop
  29
+from tornado.log import gen_log, app_log
30 30
 from tornado import stack_context
31 31
 from tornado.util import b, bytes_type
32 32
 
@@ -133,7 +133,7 @@ def connect(self, address, callback=None):
133 133
             # localhost, so handle them the same way as an error
134 134
             # reported later in _handle_connect.
135 135
             if e.args[0] not in (errno.EINPROGRESS, errno.EWOULDBLOCK):
136  
-                logging.warning("Connect error on fd %d: %s",
  136
+                gen_log.warning("Connect error on fd %d: %s",
137 137
                                 self.socket.fileno(), e)
138 138
                 self.close()
139 139
                 return
@@ -258,7 +258,7 @@ def closed(self):
258 258
 
259 259
     def _handle_events(self, fd, events):
260 260
         if not self.socket:
261  
-            logging.warning("Got events for closed stream %d", fd)
  261
+            gen_log.warning("Got events for closed stream %d", fd)
262 262
             return
263 263
         try:
264 264
             if events & self.io_loop.READ:
@@ -293,7 +293,7 @@ def _handle_events(self, fd, events):
293 293
                 self._state = state
294 294
                 self.io_loop.update_handler(self.socket.fileno(), self._state)
295 295
         except Exception:
296  
-            logging.error("Uncaught exception, closing connection.",
  296
+            gen_log.error("Uncaught exception, closing connection.",
297 297
                           exc_info=True)
298 298
             self.close()
299 299
             raise
@@ -304,7 +304,7 @@ def wrapper():
304 304
             try:
305 305
                 callback(*args)
306 306
             except Exception:
307  
-                logging.error("Uncaught exception, closing connection.",
  307
+                app_log.error("Uncaught exception, closing connection.",
308 308
                               exc_info=True)
309 309
                 # Close the socket on an uncaught exception from a user callback
310 310
                 # (It would eventually get closed when the socket object is
@@ -357,7 +357,7 @@ def _handle_read(self):
357 357
             finally:
358 358
                 self._pending_callbacks -= 1
359 359
         except Exception:
360  
-            logging.warning("error on read", exc_info=True)
  360
+            gen_log.warning("error on read", exc_info=True)
361 361
             self.close()
362 362
             return
363 363
         if self._read_from_buffer():
@@ -422,7 +422,7 @@ def _read_to_buffer(self):
422 422
             chunk = self._read_from_socket()
423 423
         except socket.error, e:
424 424
             # ssl.SSLError is a subclass of socket.error
425  
-            logging.warning("Read error on %d: %s",
  425
+            gen_log.warning("Read error on %d: %s",
426 426
                             self.socket.fileno(), e)
427 427
             self.close()
428 428
             raise
@@ -431,7 +431,7 @@ def _read_to_buffer(self):
431 431
         self._read_buffer.append(chunk)
432 432
         self._read_buffer_size += len(chunk)
433 433
         if self._read_buffer_size >= self.max_buffer_size:
434  
-            logging.error("Reached maximum read buffer size")
  434
+            gen_log.error("Reached maximum read buffer size")
435 435
             self.close()
436 436
             raise IOError("Reached maximum read buffer size")
437 437
         return len(chunk)
@@ -504,7 +504,7 @@ def _handle_connect(self):
504 504
             # an error state before the socket becomes writable, so
505 505
             # in that case a connection failure would be handled by the
506 506
             # error path in _handle_events instead of here.
507  
-            logging.warning("Connect error on fd %d: %s",
  507
+            gen_log.warning("Connect error on fd %d: %s",
508 508
                             self.socket.fileno(), errno.errorcode[err])
509 509
             self.close()
510 510
             return
@@ -544,7 +544,7 @@ def _handle_write(self):
544 544
                     self._write_buffer_frozen = True
545 545
                     break
546 546
                 else:
547  
-                    logging.warning("Write error on %d: %s",
  547
+                    gen_log.warning("Write error on %d: %s",
548 548
                                     self.socket.fileno(), e)
549 549
                     self.close()
550 550
                     return
@@ -656,7 +656,7 @@ def _do_ssl_handshake(self):
656 656
                     peer = self.socket.getpeername()
657 657
                 except:
658 658
                     peer = '(not connected)'
659  
-                logging.warning("SSL Error on %d %s: %s",
  659
+                gen_log.warning("SSL Error on %d %s: %s",
660 660
                                 self.socket.fileno(), peer, err)
661 661
                 return self.close()
662 662
             raise
12  tornado/locale.py
@@ -43,11 +43,11 @@
43 43
 
44 44
 import csv
45 45
 import datetime
46  
-import logging
47 46
 import os
48 47
 import re
49 48
 
50 49
 from tornado import escape
  50
+from tornado.log import gen_log
51 51
 
52 52
 _default_locale = "en_US"
53 53
 _translations = {}
@@ -118,7 +118,7 @@ def load_translations(directory):
118 118
             continue
119 119
         locale, extension = path.split(".")
120 120
         if not re.match("[a-z]+(_[A-Z]+)?$", locale):
121  
-            logging.error("Unrecognized locale %r (path: %s)", locale,
  121
+            gen_log.error("Unrecognized locale %r (path: %s)", locale,
122 122
                           os.path.join(directory, path))
123 123
             continue
124 124
         full_path = os.path.join(directory, path)
@@ -142,13 +142,13 @@ def load_translations(directory):
142 142
             else:
143 143
                 plural = "unknown"
144 144
             if plural not in ("plural", "singular", "unknown"):
145  
-                logging.error("Unrecognized plural indicator %r in %s line %d",
  145
+                gen_log.error("Unrecognized plural indicator %r in %s line %d",
146 146
                               plural, path, i + 1)
147 147
                 continue
148 148
             _translations[locale].setdefault(plural, {})[english] = translation
149 149
         f.close()
150 150
     _supported_locales = frozenset(_translations.keys() + [_default_locale])
151  
-    logging.debug("Supported locales: %s", sorted(_supported_locales))
  151
+    gen_log.debug("Supported locales: %s", sorted(_supported_locales))
152 152
 
153 153
 
154 154
 def load_gettext_translations(directory, domain):
@@ -184,11 +184,11 @@ def load_gettext_translations(directory, domain):
184 184
             _translations[lang] = gettext.translation(domain, directory,
185 185
                                                       languages=[lang])
186 186
         except Exception, e:
187  
-            logging.error("Cannot load translation for '%s': %s", lang, str(e))
  187
+            gen_log.error("Cannot load translation for '%s': %s", lang, str(e))
188 188
             continue
189 189
     _supported_locales = frozenset(_translations.keys() + [_default_locale])
190 190
     _use_gettext = True
191  
-    logging.debug("Supported locales: %s", sorted(_supported_locales))
  191
+    gen_log.debug("Supported locales: %s", sorted(_supported_locales))
192 192
 
193 193
 
194 194
 def get_supported_locales():
29  tornado/log.py
... ...
@@ -0,0 +1,29 @@
  1
+#!/usr/bin/env python
  2
+#
  3
+# Copyright 2012 Facebook
  4
+#
  5
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
  6
+# not use this file except in compliance with the License. You may obtain
  7
+# a copy of the License at
  8
+#
  9
+#     http://www.apache.org/licenses/LICENSE-2.0
  10
+#
  11
+# Unless required by applicable law or agreed to in writing, software
  12
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14
+# License for the specific language governing permissions and limitations
  15
+# under the License.
  16
+from __future__ import absolute_import, division, with_statement
  17
+
  18
+import logging
  19
+
  20
+# Per-request logging for Tornado's HTTP servers (and potentially other servers
  21
+# in the future)
  22
+access_log = logging.getLogger("tornado.access")
  23
+
  24
+# Logging of errors from application code (i.e. uncaught exceptions from
  25
+# callbacks
  26
+app_log = logging.getLogger("tornado.application")
  27
+
  28
+# General logging, i.e. everything else
  29
+gen_log = logging.getLogger("tornado.general")
4  tornado/netutil.py
@@ -19,7 +19,6 @@
19 19
 from __future__ import absolute_import, division, with_statement
20 20
 
21 21
 import errno
22  
-import logging
23 22
 import os
24 23
 import socket
25 24
 import stat
@@ -27,6 +26,7 @@
27 26
 from tornado import process
28 27
 from tornado.ioloop import IOLoop
29 28
 from tornado.iostream import IOStream, SSLIOStream
  29
+from tornado.log import app_log
30 30
 from tornado.platform.auto import set_close_exec
31 31
 
32 32
 try:
@@ -234,7 +234,7 @@ def _handle_connection(self, connection, address):
234 234
                 stream = IOStream(connection, io_loop=self.io_loop)
235 235
             self.handle_stream(stream, address)
236 236
         except Exception:
237  
-            logging.error("Error in connection callback", exc_info=True)
  237
+            app_log.error("Error in connection callback", exc_info=True)
238 238
 
239 239
 
240 240
 def bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=128, flags=None):
4  tornado/platform/twisted.py
@@ -47,7 +47,6 @@
47 47
 from __future__ import absolute_import, division, with_statement
48 48
 
49 49
 import functools
50  
-import logging
51 50
 import time
52 51
 
53 52
 from twisted.internet.posixbase import PosixReactorBase
@@ -60,6 +59,7 @@
60 59
 
61 60
 import tornado
62 61
 import tornado.ioloop
  62
+from tornado.log import app_log
63 63
 from tornado.stack_context import NullContext
64 64
 from tornado.ioloop import IOLoop
65 65
 
@@ -80,7 +80,7 @@ def _called(self):
80 80
         try:
81 81
             self._func()
82 82
         except:
83  
-            logging.error("_called caught exception", exc_info=True)
  83
+            app_log.error("_called caught exception", exc_info=True)
84 84
 
85 85
     def getTime(self):
86 86
         return self._time
12  tornado/process.py
@@ -19,7 +19,6 @@
19 19
 from __future__ import absolute_import, division, with_statement
20 20
 
21 21
 import errno
22  
-import logging
23 22
 import os
24 23
 import sys
25 24
 import time
@@ -27,6 +26,7 @@
27 26
 from binascii import hexlify
28 27
 
29 28
 from tornado import ioloop
  29
+from tornado.log import gen_log
30 30
 
31 31
 try:
32 32
     import multiprocessing  # Python 2.6+
@@ -45,7 +45,7 @@ def cpu_count():
45 45
         return os.sysconf("SC_NPROCESSORS_CONF")
46 46
     except ValueError:
47 47
         pass
48  
-    logging.error("Could not detect number of processors; assuming 1")
  48
+    gen_log.error("Could not detect number of processors; assuming 1")
49 49
     return 1
50 50
 
51 51
 
@@ -98,7 +98,7 @@ def fork_processes(num_processes, max_restarts=100):
98 98
         raise RuntimeError("Cannot run in multiple processes: IOLoop instance "
99 99
                            "has already been initialized. You cannot call "
100 100
                            "IOLoop.instance() before calling start_processes()")
101  
-    logging.info("Starting %d processes", num_processes)
  101
+    gen_log.info("Starting %d processes", num_processes)
102 102
     children = {}
103 103
 
104 104
     def start_child(i):
@@ -128,13 +128,13 @@ def start_child(i):
128 128
             continue
129 129
         id = children.pop(pid)
130 130
         if os.WIFSIGNALED(status):
131  
-            logging.warning("child %d (pid %d) killed by signal %d, restarting",
  131
+            gen_log.warning("child %d (pid %d) killed by signal %d, restarting",
132 132
                             id, pid, os.WTERMSIG(status))
133 133
         elif os.WEXITSTATUS(status) != 0:
134  
-            logging.warning("child %d (pid %d) exited with status %d, restarting",
  134
+            gen_log.warning("child %d (pid %d) exited with status %d, restarting",
135 135
                             id, pid, os.WEXITSTATUS(status))
136 136
         else:
137  
-            logging.info("child %d (pid %d) exited normally", id, pid)
  137
+            gen_log.info("child %d (pid %d) exited normally", id, pid)
138 138
             continue
139 139
         num_restarts += 1
140 140
         if num_restarts > max_restarts:
6  tornado/simple_httpclient.py
@@ -5,6 +5,7 @@
5 5
 from tornado.httpclient import HTTPRequest, HTTPResponse, HTTPError, AsyncHTTPClient, main
6 6
 from tornado.httputil import HTTPHeaders
7 7
 from tornado.iostream import IOStream, SSLIOStream
  8
+from tornado.log import gen_log
8 9
 from tornado import stack_context
9 10
 from tornado.util import b, GzipDecompressor
10 11
 
@@ -13,7 +14,6 @@
13 14
 import contextlib
14 15
 import copy
15 16
 import functools
16  
-import logging
17 17
 import os.path
18 18
 import re
19 19
 import socket
@@ -99,7 +99,7 @@ def fetch(self, request, callback, **kwargs):
99 99
         self.queue.append((request, callback))
100 100
         self._process_queue()
101 101
         if self.queue:
102  
-            logging.debug("max_clients limit reached, request queued. "
  102
+            gen_log.debug("max_clients limit reached, request queued. "
103 103
                           "%d active, %d queued requests." % (
104 104
                     len(self.active), len(self.queue)))
105 105
 
@@ -317,7 +317,7 @@ def cleanup(self):
317 317
         try:
318 318
             yield
319 319
         except Exception, e:
320  
-            logging.warning("uncaught exception", exc_info=True)
  320
+            gen_log.warning("uncaught exception", exc_info=True)
321 321
             self._run_callback(HTTPResponse(self.request, 599, error=e,
322 322
                                 request_time=time.time() - self.start_time,
323 323
                                 ))
6  tornado/template.py
@@ -184,13 +184,13 @@ def add(x, y):
184 184
 import cStringIO
185 185
 import datetime
186 186
 import linecache
187  
-import logging
188 187
 import os.path
189 188
 import posixpath
190 189
 import re
191 190
 import threading
192 191
 
193 192
 from tornado import escape
  193
+from tornado.log import app_log
194 194
 from tornado.util import bytes_type, ObjectDict
195 195
 
196 196
 _DEFAULT_AUTOESCAPE = "xhtml_escape"
@@ -229,7 +229,7 @@ def __init__(self, template_string, name="<string>", loader=None,
229 229
                 "exec")
230 230
         except Exception:
231 231
             formatted_code = _format_code(self.code).rstrip()
232  
-            logging.error("%s code:\n%s", self.name, formatted_code)
  232
+            app_log.error("%s code:\n%s", self.name, formatted_code)
233 233
             raise
234 234
 
235 235
     def generate(self, **kwargs):
@@ -261,7 +261,7 @@ def generate(self, **kwargs):
261 261
             return execute()
262 262
         except Exception:
263 263
             formatted_code = _format_code(self.code).rstrip()
264  
-            logging.error("%s code:\n%s", self.name, formatted_code)
  264
+            app_log.error("%s code:\n%s", self.name, formatted_code)
265 265
             raise
266 266
 
267 267
     def _generate_python(self, loader, compress_whitespace):
7  tornado/testing.py
@@ -33,6 +33,7 @@
33 33
     HTTPServer = None
34 34
     IOLoop = None
35 35
     SimpleAsyncHTTPClient = None
  36
+from tornado.log import gen_log
36 37
 from tornado.stack_context import StackContext, NullContext
37 38
 from tornado.util import raise_exc_info
38 39
 import contextlib
@@ -364,7 +365,7 @@ def run(self, result=None):
364 365
         old_stream = handler.stream
365 366
         try:
366 367
             handler.stream = StringIO()
367  
-            logging.info("RUNNING TEST: " + str(self))
  368
+            gen_log.info("RUNNING TEST: " + str(self))
368 369
             old_error_count = len(result.failures) + len(result.errors)
369 370
             super(LogTrapTestCase, self).run(result)
370 371
             new_error_count = len(result.failures) + len(result.errors)
@@ -440,9 +441,9 @@ def main(**kwargs):
440 441
             unittest.main(defaultTest="all", argv=argv, **kwargs)
441 442
     except SystemExit, e:
442 443
         if e.code == 0:
443  
-            logging.info('PASS')
  444
+            gen_log.info('PASS')
444 445
         else:
445  
-            logging.error('FAIL')
  446
+            gen_log.error('FAIL')
446 447
         if not options.autoreload:
447 448
             raise
448 449
     if options.autoreload:
32  tornado/web.py
@@ -63,7 +63,6 @@ def get(self):
63 63
 import hmac
64 64
 import httplib
65 65
 import itertools
66  
-import logging
67 66
 import mimetypes
68 67
 import os.path
69 68
 import re
@@ -80,6 +79,7 @@ def get(self):
80 79
 
81 80
 from tornado import escape
82 81
 from tornado import locale
  82
+from tornado.log import access_log, app_log, gen_log
83 83
 from tornado import stack_context
84 84
 from tornado import template
85 85
 from tornado.escape import utf8, _unicode
@@ -736,7 +736,7 @@ def send_error(self, status_code=500, **kwargs):
736 736
         Additional keyword arguments are passed through to `write_error`.
737 737
         """
738 738
         if self._headers_written:
739  
-            logging.error("Cannot send error response after headers written")
  739
+            gen_log.error("Cannot send error response after headers written")
740 740
             if not self._finished:
741 741
                 self.finish()
742 742
             return
@@ -745,7 +745,7 @@ def send_error(self, status_code=500, **kwargs):
745 745
         try:
746 746
             self.write_error(status_code, **kwargs)
747 747
         except Exception:
748  
-            logging.error("Uncaught exception in write_error", exc_info=True)
  748
+            app_log.error("Uncaught exception in write_error", exc_info=True)
749 749
         if not self._finished:
750 750
             self.finish()
751 751
 
@@ -985,7 +985,7 @@ def wrapper(*args, **kwargs):
985 985
                 return callback(*args, **kwargs)
986 986
             except Exception, e:
987 987
                 if self._headers_written:
988  
-                    logging.error("Exception after headers written",
  988
+                    app_log.error("Exception after headers written",
989 989
                                   exc_info=True)
990 990
                 else:
991 991
                     self._handle_request_exception(e)
@@ -1074,14 +1074,14 @@ def _handle_request_exception(self, e):
1074 1074
             if e.log_message:
1075 1075
                 format = "%d %s: " + e.log_message
1076 1076
                 args = [e.status_code, self._request_summary()] + list(e.args)
1077  
-                logging.warning(format, *args)
  1077
+                gen_log.warning(format, *args)
1078 1078
             if e.status_code not in httplib.responses:
1079  
-                logging.error("Bad HTTP status code: %d", e.status_code)
  1079
+                gen_log.error("Bad HTTP status code: %d", e.status_code)
1080 1080
                 self.send_error(500, exc_info=sys.exc_info())
1081 1081
             else:
1082 1082
                 self.send_error(e.status_code, exc_info=sys.exc_info())
1083 1083
         else:
1084  
-            logging.error("Uncaught exception %s\n%r", self._request_summary(),
  1084
+            app_log.error("Uncaught exception %s\n%r", self._request_summary(),
1085 1085
                           self.request, exc_info=True)
1086 1086
             self.send_error(500, exc_info=sys.exc_info())
1087 1087
 
@@ -1328,7 +1328,7 @@ def add_handlers(self, host_pattern, host_handlers):
1328 1328
             handlers.append(spec)
1329 1329
             if spec.name:
1330 1330
                 if spec.name in self.named_handlers:
1331  
-                    logging.warning(
  1331
+                    app_log.warning(
1332 1332
                         "Multiple handlers named %s; replacing previous value",
1333 1333
                         spec.name)
1334 1334
                 self.named_handlers[spec.name] = spec
@@ -1452,11 +1452,11 @@ def log_request(self, handler):
1452 1452
             self.settings["log_function"](handler)
1453 1453
             return
1454 1454
         if handler.get_status() < 400:
1455  
-            log_method = logging.info
  1455
+            log_method = access_log.info
1456 1456
         elif handler.get_status() < 500:
1457  
-            log_method = logging.warning
  1457
+            log_method = access_log.warning
1458 1458
         else:
1459  
-            log_method = logging.error
  1459
+            log_method = access_log.error
1460 1460
         request_time = 1000.0 * handler.request.request_time()
1461 1461
         log_method("%d %s %.2fms", handler.get_status(),
1462 1462
                    handler._request_summary(), request_time)
@@ -1655,7 +1655,7 @@ def get_version(cls, settings, path):
1655 1655
                     hashes[abs_path] = hashlib.md5(f.read()).hexdigest()
1656 1656
                     f.close()
1657 1657
                 except Exception:
1658  
-                    logging.error("Could not open static file %r", path)
  1658
+                    gen_log.error("Could not open static file %r", path)
1659 1659
                     hashes[abs_path] = None
1660 1660
             hsh = hashes.get(abs_path)
1661 1661
             if hsh:
@@ -2039,11 +2039,11 @@ def decode_signed_value(secret, name, value, max_age_days=31):
2039 2039
         return None
2040 2040
     signature = _create_signature(secret, name, parts[0], parts[1])
2041 2041
     if not _time_independent_equals(parts[2], signature):
2042  
-        logging.warning("Invalid cookie signature %r", value)
  2042
+        gen_log.warning("Invalid cookie signature %r", value)
2043 2043
         return None
2044 2044
     timestamp = int(parts[1])
2045 2045
     if timestamp < time.time() - max_age_days * 86400:
2046  
-        logging.warning("Expired cookie %r", value)
  2046
+        gen_log.warning("Expired cookie %r", value)
2047 2047
         return None
2048 2048
     if timestamp > time.time() + 31 * 86400:
2049 2049
         # _cookie_signature does not hash a delimiter between the
@@ -2051,10 +2051,10 @@ def decode_signed_value(secret, name, value, max_age_days=31):
2051 2051
         # digits from the payload to the timestamp without altering the
2052 2052
         # signature.  For backwards compatibility, sanity-check timestamp
2053 2053
         # here instead of modifying _cookie_signature.
2054  
-        logging.warning("Cookie timestamp in future; possible tampering %r", value)
  2054
+        gen_log.warning("Cookie timestamp in future; possible tampering %r", value)
2055 2055
         return None
2056 2056
     if parts[1].startswith(b("0")):
2057  
-        logging.warning("Tampered cookie %r", value)
  2057
+        gen_log.warning("Tampered cookie %r", value)
2058 2058
         return None
2059 2059
     try:
2060 2060
         return base64.b64decode(parts[0])
10  tornado/websocket.py
@@ -23,13 +23,13 @@
23 23
 import array
24 24
 import functools
25 25
 import hashlib
26  
-import logging
27 26
 import struct
28 27
 import time
29 28
 import base64
30 29
 import tornado.escape
31 30
 import tornado.web
32 31
 
  32
+from tornado.log import gen_log, app_log
33 33
 from tornado.util import bytes_type, b
34 34
 
35 35
 
@@ -257,7 +257,7 @@ def wrapper(*args, **kwargs):
257 257
             try:
258 258
                 return callback(*args, **kwargs)
259 259
             except Exception:
260  
-                logging.error("Uncaught exception in %s",
  260
+                app_log.error("Uncaught exception in %s",
261 261
                               self.request.path, exc_info=True)
262 262
                 self._abort()
263 263
         return wrapper
@@ -289,7 +289,7 @@ def accept_connection(self):
289 289
         try:
290 290
             self._handle_websocket_headers()
291 291
         except ValueError:
292  
-            logging.debug("Malformed WebSocket request received")
  292
+            gen_log.debug("Malformed WebSocket request received")
293 293
             self._abort()
294 294
             return
295 295
 
@@ -344,7 +344,7 @@ def _handle_challenge(self, challenge):
344 344
         try:
345 345
             challenge_response = self.challenge_response(challenge)
346 346
         except ValueError:
347  
-            logging.debug("Malformed key data in WebSocket request")
  347
+            gen_log.debug("Malformed key data in WebSocket request")
348 348
             self._abort()
349 349
             return
350 350
         self._write_response(challenge_response)
@@ -457,7 +457,7 @@ def accept_connection(self):
457 457
             self._handle_websocket_headers()
458 458
             self._accept_connection()
459 459
         except ValueError:
460  
-            logging.debug("Malformed WebSocket request received")
  460
+            gen_log.debug("Malformed WebSocket request received")
461 461
             self._abort()
462 462
             return
463 463
 
8  tornado/wsgi.py
@@ -33,7 +33,6 @@
33 33
 
34 34
 import Cookie
35 35
 import httplib
36  
-import logging
37 36
 import sys
38 37
 import time
39 38
 import tornado
@@ -41,6 +40,7 @@
41 40
 
42 41
 from tornado import escape
43 42
 from tornado import httputil
  43
+from tornado.log import access_log
44 44
 from tornado import web
45 45
 from tornado.escape import native_str, utf8, parse_qs_bytes
46 46
 from tornado.util import b, bytes_type
@@ -302,11 +302,11 @@ def environ(request):
302 302
 
303 303
     def _log(self, status_code, request):
304 304
         if status_code < 400:
305  
-            log_method = logging.info
  305
+            log_method = access_log.info
306 306
         elif status_code < 500:
307  
-            log_method = logging.warning
  307
+            log_method = access_log.warning
308 308
         else:
309  
-            log_method = logging.error
  309
+            log_method = access_log.error
310 310
         request_time = 1000.0 * request.request_time()
311 311
         summary = request.method + " " + request.uri + " (" + \
312 312
             request.remote_ip + ")"

0 notes on commit 9b944aa

Please sign in to comment.
Something went wrong with that request. Please try again.