]> git.ipfire.org Git - thirdparty/tornado.git/commitdiff
Send all logging to the root logger instead of per-module loggers.
authorBen Darnell <bdarnell@beaker.local>
Tue, 20 Apr 2010 22:40:33 +0000 (15:40 -0700)
committerBen Darnell <bdarnell@beaker.local>
Tue, 20 Apr 2010 22:40:33 +0000 (15:40 -0700)
This undoes the effect of
http://github.com/facebook/tornado/commit/e391fd289ed085671344504cc5b1fa84f5a3c774

Per-module loggers are problematic because only the top-level convenience
logging.{error,warning,...} functions configure logging on-demand, so
an app that only uses per-module loggers will produce no output except
"no handlers found for logger X".  Since tornado.ioloop swallows and logs
all exceptions, this makes it too hard to tell what's going on for apps
that do not configure logging explicitly.

Instead of setting log levels on individual module's loggers,
logging.Handler.addFilter can be used with a filter that examines
the module attribute of the log record.

12 files changed:
tornado/auth.py
tornado/autoreload.py
tornado/database.py
tornado/httpclient.py
tornado/httpserver.py
tornado/ioloop.py
tornado/iostream.py
tornado/locale.py
tornado/template.py
tornado/web.py
tornado/websocket.py
tornado/wsgi.py

index ab5948e541f6e945e01ee1792b31c82a32756fa5..dfde6af92a08ac0fa19b3623d8d83ef1aaa33b7c 100644 (file)
@@ -58,8 +58,6 @@ import urllib
 import urlparse
 import uuid
 
-_log = logging.getLogger("tornado.auth")
-
 class OpenIdMixin(object):
     """Abstract implementation of OpenID and Attribute Exchange.
 
@@ -146,7 +144,7 @@ class OpenIdMixin(object):
 
     def _on_authentication_verified(self, callback, response):
         if response.error or u"is_valid:true" not in response.body:
-            _log.warning("Invalid OpenID response: %s", response.error or
+            logging.warning("Invalid OpenID response: %s", response.error or
                             response.body)
             callback(None)
             return
@@ -233,12 +231,12 @@ class OAuthMixin(object):
         request_key = self.get_argument("oauth_token")
         request_cookie = self.get_cookie("_oauth_request_token")
         if not request_cookie:
-            _log.warning("Missing OAuth request token cookie")
+            logging.warning("Missing OAuth request token cookie")
             callback(None)
             return
         cookie_key, cookie_secret = request_cookie.split("|")
         if cookie_key != request_key:
-            _log.warning("Request token does not match cookie")
+            logging.warning("Request token does not match cookie")
             callback(None)
             return
         token = dict(key=cookie_key, secret=cookie_secret)
@@ -290,7 +288,7 @@ class OAuthMixin(object):
 
     def _on_access_token(self, callback, response):
         if response.error:
-            _log.warning("Could not fetch access token")
+            logging.warning("Could not fetch access token")
             callback(None)
             return
         access_token = _oauth_parse_response(response.body)
@@ -442,7 +440,7 @@ class TwitterMixin(OAuthMixin):
 
     def _on_twitter_request(self, callback, response):
         if response.error:
-            _log.warning("Error response %s fetching %s", response.error,
+            logging.warning("Error response %s fetching %s", response.error,
                             response.request.url)
             callback(None)
             return
@@ -562,7 +560,7 @@ class FriendFeedMixin(OAuthMixin):
 
     def _on_friendfeed_request(self, callback, response):
         if response.error:
-            _log.warning("Error response %s fetching %s", response.error,
+            logging.warning("Error response %s fetching %s", response.error,
                             response.request.url)
             callback(None)
             return
@@ -820,17 +818,17 @@ class FacebookMixin(object):
 
     def _parse_response(self, callback, response):
         if response.error:
-            _log.warning("HTTP error from Facebook: %s", response.error)
+            logging.warning("HTTP error from Facebook: %s", response.error)
             callback(None)
             return
         try:
             json = escape.json_decode(response.body)
         except:
-            _log.warning("Invalid JSON from Facebook: %r", response.body)
+            logging.warning("Invalid JSON from Facebook: %r", response.body)
             callback(None)
             return
         if isinstance(json, dict) and json.get("error_code"):
-            _log.warning("Facebook error: %d: %r", json["error_code"],
+            logging.warning("Facebook error: %d: %r", json["error_code"],
                             json.get("error_msg"))
             callback(None)
             return
index 231cfe892cebf20b0141214b113cfe6bfa937f91..70ff734205f09762e93202843d0cf84ee1b4f8fe 100644 (file)
@@ -29,8 +29,6 @@ import os.path
 import sys
 import types
 
-_log = logging.getLogger('tornado.autoreload')
-
 def start(io_loop=None, check_time=500):
     """Restarts the process automatically when a module is modified.
 
@@ -69,7 +67,7 @@ def _reload_on_update(io_loop, modify_times):
             modify_times[path] = modified
             continue
         if modify_times[path] != modified:
-            _log.info("%s modified; restarting server", path)
+            logging.info("%s modified; restarting server", path)
             _reload_attempted = True
             for fd in io_loop._handlers.keys():
                 try:
index 3f78e00b94ecfa62e859613c850b9378789140b4..190a804da7706503ba3a51a119dc3073fee54444 100644 (file)
@@ -24,8 +24,6 @@ import MySQLdb.cursors
 import itertools
 import logging
 
-_log = logging.getLogger('tornado.database')
-
 class Connection(object):
     """A lightweight wrapper around MySQLdb DB-API connections.
 
@@ -72,7 +70,7 @@ class Connection(object):
         try:
             self.reconnect()
         except:
-            _log.error("Cannot connect to MySQL on %s", self.host,
+            logging.error("Cannot connect to MySQL on %s", self.host,
                           exc_info=True)
 
     def __del__(self):
@@ -151,7 +149,7 @@ class Connection(object):
         try:
             return cursor.execute(query, parameters)
         except OperationalError:
-            _log.error("Error connecting to MySQL on %s", self.host)
+            logging.error("Error connecting to MySQL on %s", self.host)
             self.close()
             raise
 
index 658513eb79992071cd585433aa611ec71902a6d3..ac4ad985a26b4f5f9f84acd009453a5bdb121a0b 100644 (file)
@@ -29,8 +29,6 @@ import pycurl
 import time
 import weakref
 
-_log = logging.getLogger('tornado.httpclient')
-
 class HTTPClient(object):
     """A blocking HTTP client backed with pycurl.
 
@@ -348,7 +346,7 @@ class CurlError(HTTPError):
 
 def _curl_create(max_simultaneous_connections=None):
     curl = pycurl.Curl()
-    if _log.isEnabledFor(logging.DEBUG):
+    if logging.getLogger().isEnabledFor(logging.DEBUG):
         curl.setopt(pycurl.VERBOSE, 1)
         curl.setopt(pycurl.DEBUGFUNCTION, _curl_debug)
     curl.setopt(pycurl.MAXCONNECTS, max_simultaneous_connections or 5)
@@ -423,11 +421,11 @@ def _curl_setup_request(curl, request, buffer, headers):
         userpwd = "%s:%s" % (request.auth_username, request.auth_password)
         curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
         curl.setopt(pycurl.USERPWD, userpwd)
-        _log.info("%s %s (username: %r)", request.method, request.url,
+        logging.info("%s %s (username: %r)", request.method, request.url,
                      request.auth_username)
     else:
         curl.unsetopt(pycurl.USERPWD)
-        _log.info("%s %s", request.method, request.url)
+        logging.info("%s %s", request.method, request.url)
     if request.prepare_curl_callback is not None:
         request.prepare_curl_callback(curl)
 
@@ -440,7 +438,7 @@ def _curl_header_callback(headers, header_line):
         return
     parts = header_line.split(":", 1)
     if len(parts) != 2:
-        _log.warning("Invalid HTTP response header line %r", header_line)
+        logging.warning("Invalid HTTP response header line %r", header_line)
         return
     name = parts[0].strip()
     value = parts[1].strip()
@@ -453,12 +451,12 @@ def _curl_header_callback(headers, header_line):
 def _curl_debug(debug_type, debug_msg):
     debug_types = ('I', '<', '>', '<', '>')
     if debug_type == 0:
-        _log.debug('%s', debug_msg.strip())
+        logging.debug('%s', debug_msg.strip())
     elif debug_type in (1, 2):
         for line in debug_msg.splitlines():
-            _log.debug('%s %s', debug_types[debug_type], line)
+            logging.debug('%s %s', debug_types[debug_type], line)
     elif debug_type == 4:
-        _log.debug('%s %r', debug_types[debug_type], debug_msg)
+        logging.debug('%s %r', debug_types[debug_type], debug_msg)
 
 
 def _utf8(value):
index dab9945b72b0bd489e55e923072a0f6494bd122e..70e23c20a2aea91ba56cf06a29d62abba8366bfd 100644 (file)
@@ -40,8 +40,6 @@ try:
 except ImportError:
     ssl = None
 
-_log = logging.getLogger('tornado.httpserver')
-
 class HTTPServer(object):
     """A non-blocking, single-threaded HTTP server.
 
@@ -172,16 +170,16 @@ class HTTPServer(object):
             try:
                 num_processes = os.sysconf("SC_NPROCESSORS_CONF")
             except ValueError:
-                _log.error("Could not get num processors from sysconf; "
+                logging.error("Could not get num processors from sysconf; "
                               "running with one process")
                 num_processes = 1
         if num_processes > 1 and ioloop.IOLoop.initialized():
-            _log.error("Cannot run in multiple processes: IOLoop instance "
+            logging.error("Cannot run in multiple processes: IOLoop instance "
                           "has already been initialized. You cannot call "
                           "IOLoop.instance() before calling start()")
             num_processes = 1
         if num_processes > 1:
-            _log.info("Pre-forking %d server processes", num_processes)
+            logging.info("Pre-forking %d server processes", num_processes)
             for i in range(num_processes):
                 if os.fork() == 0:
                     self.io_loop = ioloop.IOLoop.instance()
@@ -218,7 +216,7 @@ class HTTPServer(object):
                 HTTPConnection(stream, address, self.request_callback,
                                self.no_keep_alive, self.xheaders)
             except:
-                _log.error("Error in connection callback", exc_info=True)
+                logging.error("Error in connection callback", exc_info=True)
 
 
 class HTTPConnection(object):
@@ -321,13 +319,13 @@ class HTTPConnection(object):
             if not part: continue
             eoh = part.find("\r\n\r\n")
             if eoh == -1:
-                _log.warning("multipart/form-data missing headers")
+                logging.warning("multipart/form-data missing headers")
                 continue
             headers = HTTPHeaders.parse(part[:eoh])
             name_header = headers.get("Content-Disposition", "")
             if not name_header.startswith("form-data;") or \
                not part.endswith("\r\n"):
-                _log.warning("Invalid multipart/form-data")
+                logging.warning("Invalid multipart/form-data")
                 continue
             value = part[eoh + 4:-2]
             name_values = {}
@@ -335,7 +333,7 @@ class HTTPConnection(object):
                 name, name_value = name_part.strip().split("=", 1)
                 name_values[name] = name_value.strip('"').decode("utf-8")
             if not name_values.get("name"):
-                _log.warning("multipart/form-data value missing name")
+                logging.warning("multipart/form-data value missing name")
                 continue
             name = name_values["name"]
             if name_values.get("filename"):
index e94c17372e9faa1689075c52b804cd4b1a106f5b..7cfd707a05d75049ba21f8bf9798b40f403aef08 100644 (file)
@@ -32,8 +32,6 @@ except ImportError:
     else:
         raise
 
-_log = logging.getLogger("tornado.ioloop")
-
 class IOLoop(object):
     """A level-triggered I/O loop.
 
@@ -154,7 +152,7 @@ class IOLoop(object):
         try:
             self._impl.unregister(fd)
         except (OSError, IOError):
-            _log.debug("Error deleting fd from IOLoop", exc_info=True)
+            logging.debug("Error deleting fd from IOLoop", exc_info=True)
 
     def start(self):
         """Starts the I/O loop.
@@ -198,7 +196,7 @@ class IOLoop(object):
                 event_pairs = self._impl.poll(poll_timeout)
             except Exception, e:
                 if hasattr(e, 'errno') and e.errno == errno.EINTR:
-                    _log.warning("Interrupted system call", exc_info=1)
+                    logging.warning("Interrupted system call", exc_info=1)
                     continue
                 else:
                     raise
@@ -219,10 +217,10 @@ class IOLoop(object):
                         # Happens when the client closes the connection
                         pass
                     else:
-                        _log.error("Exception in I/O handler for fd %d",
+                        logging.error("Exception in I/O handler for fd %d",
                                       fd, exc_info=True)
                 except:
-                    _log.error("Exception in I/O handler for fd %d",
+                    logging.error("Exception in I/O handler for fd %d",
                                   fd, exc_info=True)
         # reset the stopped flag so another start/stop pair can be issued
         self._stopped = False
@@ -290,7 +288,7 @@ class IOLoop(object):
         The exception itself is not passed explicitly, but is available
         in sys.exc_info.
         """
-        _log.error("Exception in callback %r", callback, exc_info=True)
+        logging.error("Exception in callback %r", callback, exc_info=True)
 
     def _read_waker(self, fd, events):
         try:
@@ -348,7 +346,7 @@ class PeriodicCallback(object):
         except (KeyboardInterrupt, SystemExit):
             raise
         except:
-            _log.error("Error in periodic callback", exc_info=True)
+            logging.error("Error in periodic callback", exc_info=True)
         self.start()
 
 
@@ -479,5 +477,5 @@ else:
         # All other systems
         import sys
         if "linux" in sys.platform:
-            _log.warning("epoll module not found; using select()")
+            logging.warning("epoll module not found; using select()")
         _poll = _Select
index af7c6edbfee7b580ae909dda9a0324e4d621e45f..767f36dc3b61c6a0dd8a94740c57304488cb50f9 100644 (file)
@@ -21,8 +21,6 @@ import ioloop
 import logging
 import socket
 
-_log = logging.getLogger('tornado.iostream')
-
 class IOStream(object):
     """A utility class to write to and read from a non-blocking socket.
 
@@ -139,7 +137,7 @@ class IOStream(object):
 
     def _handle_events(self, fd, events):
         if not self.socket:
-            _log.warning("Got events for closed stream %d", fd)
+            logging.warning("Got events for closed stream %d", fd)
             return
         if events & self.io_loop.READ:
             self._handle_read()
@@ -168,7 +166,7 @@ class IOStream(object):
             if e[0] in (errno.EWOULDBLOCK, errno.EAGAIN):
                 return
             else:
-                _log.warning("Read error on %d: %s",
+                logging.warning("Read error on %d: %s",
                                 self.socket.fileno(), e)
                 self.close()
                 return
@@ -177,7 +175,7 @@ class IOStream(object):
             return
         self._read_buffer += chunk
         if len(self._read_buffer) >= self.max_buffer_size:
-            _log.error("Reached maximum read buffer size")
+            logging.error("Reached maximum read buffer size")
             self.close()
             return
         if self._read_bytes:
@@ -205,7 +203,7 @@ class IOStream(object):
                 if e[0] in (errno.EWOULDBLOCK, errno.EAGAIN):
                     break
                 else:
-                    _log.warning("Write error on %d: %s",
+                    logging.warning("Write error on %d: %s",
                                     self.socket.fileno(), e)
                     self.close()
                     return
index 6a8537d7500981941a68cab6624c78ad8fc23842..488ea2c599c2f8e7df23fcc95c3d8f3095f4cd23 100644 (file)
@@ -51,8 +51,6 @@ _translations = {}
 _supported_locales = frozenset([_default_locale])
 _use_gettext = False
 
-_log = logging.getLogger('tornado.locale')
-
 def get(*locale_codes):
     """Returns the closest match for the given locale codes.
 
@@ -112,7 +110,7 @@ def load_translations(directory):
         if not path.endswith(".csv"): continue
         locale, extension = path.split(".")
         if locale not in LOCALE_NAMES:
-            _log.error("Unrecognized locale %r (path: %s)", locale,
+            logging.error("Unrecognized locale %r (path: %s)", locale,
                           os.path.join(directory, path))
             continue
         f = open(os.path.join(directory, path), "r")
@@ -126,13 +124,13 @@ def load_translations(directory):
             else:
                 plural = "unknown"
             if plural not in ("plural", "singular", "unknown"):
-                _log.error("Unrecognized plural indicator %r in %s line %d",
+                logging.error("Unrecognized plural indicator %r in %s line %d",
                               plural, path, i + 1)
                 continue
             _translations[locale].setdefault(plural, {})[english] = translation
         f.close()
     _supported_locales = frozenset(_translations.keys() + [_default_locale])
-    _log.info("Supported locales: %s", sorted(_supported_locales))
+    logging.info("Supported locales: %s", sorted(_supported_locales))
 
 def load_gettext_translations(directory, domain):
     """Loads translations from gettext's locale tree
@@ -168,7 +166,7 @@ def load_gettext_translations(directory, domain):
             continue
     _supported_locales = frozenset(_translations.keys() + [_default_locale])
     _use_gettext = True
-    _log.info("Supported locales: %s", sorted(_supported_locales))
+    logging.info("Supported locales: %s", sorted(_supported_locales))
 
 
 def get_supported_locales(cls):
index 7ed56cfa69290a174b204436eecf0b4b7d3b003d..b807cc68a25590c8b36d650cc228b1f637132e79 100644 (file)
@@ -88,8 +88,6 @@ import logging
 import os.path
 import re
 
-_log = logging.getLogger('tornado.template')
-
 class Template(object):
     """A compiled template.
 
@@ -109,7 +107,7 @@ class Template(object):
             self.compiled = compile(self.code, self.name, "exec")
         except:
             formatted_code = _format_code(self.code).rstrip()
-            _log.error("%s code:\n%s", self.name, formatted_code)
+            logging.error("%s code:\n%s", self.name, formatted_code)
             raise
 
     def generate(self, **kwargs):
@@ -128,7 +126,7 @@ class Template(object):
             return execute()
         except:
             formatted_code = _format_code(self.code).rstrip()
-            _log.error("%s code:\n%s", self.name, formatted_code)
+            logging.error("%s code:\n%s", self.name, formatted_code)
             raise
 
     def _generate_python(self, loader, compress_whitespace):
index 7559fae8a576dc9067fa48dabbe5b90cba12ae61..303e278b65d12b10828d59b4bb4d0c348f477af5 100644 (file)
@@ -70,8 +70,6 @@ import urllib
 import urlparse
 import uuid
 
-_log = logging.getLogger('tornado.web')
-
 class RequestHandler(object):
     """Subclass this class and define get() or post() to make a handler.
 
@@ -286,11 +284,11 @@ class RequestHandler(object):
         else:
             signature = self._cookie_signature(parts[0], parts[1])
         if not _time_independent_equals(parts[2], signature):
-            _log.warning("Invalid cookie signature %r", value)
+            logging.warning("Invalid cookie signature %r", value)
             return None
         timestamp = int(parts[1])
         if timestamp < time.time() - 31 * 86400:
-            _log.warning("Expired cookie %r", value)
+            logging.warning("Expired cookie %r", value)
             return None
         try:
             return base64.b64decode(parts[0])
@@ -505,7 +503,7 @@ class RequestHandler(object):
         for your application.
         """
         if self._headers_written:
-            _log.error("Cannot send error response after headers written")
+            logging.error("Cannot send error response after headers written")
             if not self._finished:
                 self.finish()
             return
@@ -679,7 +677,7 @@ class RequestHandler(object):
                 hashes[path] = hashlib.md5(f.read()).hexdigest()
                 f.close()
             except:
-                _log.error("Could not open static file %r", path)
+                logging.error("Could not open static file %r", path)
                 hashes[path] = None
         base = self.request.protocol + "://" + self.request.host \
             if getattr(self, "include_host", False) else ""
@@ -703,7 +701,7 @@ class RequestHandler(object):
                 return callback(*args, **kwargs)
             except Exception, e:
                 if self._headers_written:
-                    _log.error("Exception after headers written",
+                    logging.error("Exception after headers written",
                                   exc_info=True)
                 else:
                     self._handle_request_exception(e)
@@ -748,11 +746,11 @@ class RequestHandler(object):
 
     def _log(self):
         if self._status_code < 400:
-            log_method = _log.info
+            log_method = logging.info
         elif self._status_code < 500:
-            log_method = _log.warning
+            log_method = logging.warning
         else:
-            log_method = _log.error
+            log_method = logging.error
         request_time = 1000.0 * self.request.request_time()
         log_method("%d %s %.2fms", self._status_code,
                    self._request_summary(), request_time)
@@ -766,14 +764,14 @@ class RequestHandler(object):
             if e.log_message:
                 format = "%d %s: " + e.log_message
                 args = [e.status_code, self._request_summary()] + list(e.args)
-                _log.warning(format, *args)
+                logging.warning(format, *args)
             if e.status_code not in httplib.responses:
-                _log.error("Bad HTTP status code: %d", e.status_code)
+                logging.error("Bad HTTP status code: %d", e.status_code)
                 self.send_error(500, exception=e)
             else:
                 self.send_error(e.status_code, exception=e)
         else:
-            _log.error("Uncaught exception %s\n%r", self._request_summary(),
+            logging.error("Uncaught exception %s\n%r", self._request_summary(),
                           self.request, exc_info=e)
             self.send_error(500, exception=e)
 
@@ -962,7 +960,7 @@ class Application(object):
             handlers.append(spec)
             if spec.name:
                 if spec.name in self.named_handlers:
-                    _log.warning(
+                    logging.warning(
                         "Multiple handlers named %s; replacing previous value",
                         spec.name)
                 self.named_handlers[spec.name] = spec
index 38a58012cc1db885f80aab600b3a9cfec4aaca80..dfca709c44f855d356b356e6fb9bed1d5133969e 100644 (file)
@@ -19,8 +19,6 @@ import logging
 import tornado.escape
 import tornado.web
 
-_log = logging.getLogger('tornado.websocket')
-
 class WebSocketHandler(tornado.web.RequestHandler):
     """A request handler for HTML 5 Web Sockets.
 
@@ -116,7 +114,7 @@ class WebSocketHandler(tornado.web.RequestHandler):
             try:
                 return callback(*args, **kwargs)
             except Exception, e:
-                _log.error("Uncaught exception in %s",
+                logging.error("Uncaught exception in %s",
                               self.request.path, exc_info=True)
                 self.stream.close()
         return wrapper
index 24bd22d278b697193029f8b1257c2de2a04b4cba..e3f0a50b57ca3be0aad16d511cb3c0ae7121a013 100644 (file)
@@ -60,8 +60,6 @@ import time
 import urllib
 import web
 
-_log = logging.getLogger('tornado.wsgi')
-
 class WSGIApplication(web.Application):
     """A WSGI-equivalent of web.Application.
 
@@ -159,13 +157,13 @@ class HTTPRequest(object):
             if not part: continue
             eoh = part.find("\r\n\r\n")
             if eoh == -1:
-                _log.warning("multipart/form-data missing headers")
+                logging.warning("multipart/form-data missing headers")
                 continue
             headers = HTTPHeaders.parse(part[:eoh])
             name_header = headers.get("Content-Disposition", "")
             if not name_header.startswith("form-data;") or \
                not part.endswith("\r\n"):
-                _log.warning("Invalid multipart/form-data")
+                logging.warning("Invalid multipart/form-data")
                 continue
             value = part[eoh + 4:-2]
             name_values = {}
@@ -173,7 +171,7 @@ class HTTPRequest(object):
                 name, name_value = name_part.strip().split("=", 1)
                 name_values[name] = name_value.strip('"').decode("utf-8")
             if not name_values.get("name"):
-                _log.warning("multipart/form-data value missing name")
+                logging.warning("multipart/form-data value missing name")
                 continue
             name = name_values["name"]
             if name_values.get("filename"):
@@ -279,11 +277,11 @@ class WSGIContainer(object):
 
     def _log(self, status_code, request):
         if status_code < 400:
-            log_method = _log.info
+            log_method = logging.info
         elif status_code < 500:
-            log_method = _log.warning
+            log_method = logging.warning
         else:
-            log_method = _log.error
+            log_method = logging.error
         request_time = 1000.0 * request.request_time()
         summary = request.method + " " + request.uri + " (" + \
             request.remote_ip + ")"