log.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. """Logging support for Tornado.
  17. Tornado uses three logger streams:
  18. * ``tornado.access``: Per-request logging for Tornado's HTTP servers (and
  19. potentially other servers in the future)
  20. * ``tornado.application``: Logging of errors from application code (i.e.
  21. uncaught exceptions from callbacks)
  22. * ``tornado.general``: General-purpose logging, including any errors
  23. or warnings from Tornado itself.
  24. These streams may be configured independently using the standard library's
  25. `logging` module. For example, you may wish to send ``tornado.access`` logs
  26. to a separate file for analysis.
  27. """
  28. from __future__ import absolute_import, division, print_function, with_statement
  29. import logging
  30. import logging.handlers
  31. import sys
  32. from tornado.escape import _unicode
  33. from tornado.util import unicode_type, basestring_type
  34. try:
  35. import curses
  36. except ImportError:
  37. curses = None
  38. # Logger objects for internal tornado use
  39. access_log = logging.getLogger("tornado.access")
  40. app_log = logging.getLogger("tornado.application")
  41. gen_log = logging.getLogger("tornado.general")
  42. def _stderr_supports_color():
  43. color = False
  44. if curses and hasattr(sys.stderr, 'isatty') and sys.stderr.isatty():
  45. try:
  46. curses.setupterm()
  47. if curses.tigetnum("colors") > 0:
  48. color = True
  49. except Exception:
  50. pass
  51. return color
  52. def _safe_unicode(s):
  53. try:
  54. return _unicode(s)
  55. except UnicodeDecodeError:
  56. return repr(s)
  57. class LogFormatter(logging.Formatter):
  58. """Log formatter used in Tornado.
  59. Key features of this formatter are:
  60. * Color support when logging to a terminal that supports it.
  61. * Timestamps on every log line.
  62. * Robust against str/bytes encoding problems.
  63. This formatter is enabled automatically by
  64. `tornado.options.parse_command_line` (unless ``--logging=none`` is
  65. used).
  66. """
  67. DEFAULT_FORMAT = '%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s'
  68. DEFAULT_DATE_FORMAT = '%y%m%d %H:%M:%S'
  69. DEFAULT_COLORS = {
  70. logging.DEBUG: 4, # Blue
  71. logging.INFO: 2, # Green
  72. logging.WARNING: 3, # Yellow
  73. logging.ERROR: 1, # Red
  74. }
  75. def __init__(self, color=True, fmt=DEFAULT_FORMAT,
  76. datefmt=DEFAULT_DATE_FORMAT, colors=DEFAULT_COLORS):
  77. r"""
  78. :arg bool color: Enables color support.
  79. :arg string fmt: Log message format.
  80. It will be applied to the attributes dict of log records. The
  81. text between ``%(color)s`` and ``%(end_color)s`` will be colored
  82. depending on the level if color support is on.
  83. :arg dict colors: color mappings from logging level to terminal color
  84. code
  85. :arg string datefmt: Datetime format.
  86. Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.
  87. .. versionchanged:: 3.2
  88. Added ``fmt`` and ``datefmt`` arguments.
  89. """
  90. logging.Formatter.__init__(self, datefmt=datefmt)
  91. self._fmt = fmt
  92. self._colors = {}
  93. if color and _stderr_supports_color():
  94. # The curses module has some str/bytes confusion in
  95. # python3. Until version 3.2.3, most methods return
  96. # bytes, but only accept strings. In addition, we want to
  97. # output these strings with the logging module, which
  98. # works with unicode strings. The explicit calls to
  99. # unicode() below are harmless in python2 but will do the
  100. # right conversion in python 3.
  101. fg_color = (curses.tigetstr("setaf") or
  102. curses.tigetstr("setf") or "")
  103. if (3, 0) < sys.version_info < (3, 2, 3):
  104. fg_color = unicode_type(fg_color, "ascii")
  105. for levelno, code in colors.items():
  106. self._colors[levelno] = unicode_type(curses.tparm(fg_color, code), "ascii")
  107. self._normal = unicode_type(curses.tigetstr("sgr0"), "ascii")
  108. else:
  109. self._normal = ''
  110. def format(self, record):
  111. try:
  112. message = record.getMessage()
  113. assert isinstance(message, basestring_type) # guaranteed by logging
  114. # Encoding notes: The logging module prefers to work with character
  115. # strings, but only enforces that log messages are instances of
  116. # basestring. In python 2, non-ascii bytestrings will make
  117. # their way through the logging framework until they blow up with
  118. # an unhelpful decoding error (with this formatter it happens
  119. # when we attach the prefix, but there are other opportunities for
  120. # exceptions further along in the framework).
  121. #
  122. # If a byte string makes it this far, convert it to unicode to
  123. # ensure it will make it out to the logs. Use repr() as a fallback
  124. # to ensure that all byte strings can be converted successfully,
  125. # but don't do it by default so we don't add extra quotes to ascii
  126. # bytestrings. This is a bit of a hacky place to do this, but
  127. # it's worth it since the encoding errors that would otherwise
  128. # result are so useless (and tornado is fond of using utf8-encoded
  129. # byte strings whereever possible).
  130. record.message = _safe_unicode(message)
  131. except Exception as e:
  132. record.message = "Bad message (%r): %r" % (e, record.__dict__)
  133. record.asctime = self.formatTime(record, self.datefmt)
  134. if record.levelno in self._colors:
  135. record.color = self._colors[record.levelno]
  136. record.end_color = self._normal
  137. else:
  138. record.color = record.end_color = ''
  139. formatted = self._fmt % record.__dict__
  140. if record.exc_info:
  141. if not record.exc_text:
  142. record.exc_text = self.formatException(record.exc_info)
  143. if record.exc_text:
  144. # exc_text contains multiple lines. We need to _safe_unicode
  145. # each line separately so that non-utf8 bytes don't cause
  146. # all the newlines to turn into '\n'.
  147. lines = [formatted.rstrip()]
  148. lines.extend(_safe_unicode(ln) for ln in record.exc_text.split('\n'))
  149. formatted = '\n'.join(lines)
  150. return formatted.replace("\n", "\n ")
  151. def enable_pretty_logging(options=None, logger=None):
  152. """Turns on formatted logging output as configured.
  153. This is called automatically by `tornado.options.parse_command_line`
  154. and `tornado.options.parse_config_file`.
  155. """
  156. if options is None:
  157. from tornado.options import options
  158. if options.logging is None or options.logging.lower() == 'none':
  159. return
  160. if logger is None:
  161. logger = logging.getLogger()
  162. logger.setLevel(getattr(logging, options.logging.upper()))
  163. if options.log_file_prefix:
  164. rotate_mode = options.log_rotate_mode
  165. if rotate_mode == 'size':
  166. channel = logging.handlers.RotatingFileHandler(
  167. filename=options.log_file_prefix,
  168. maxBytes=options.log_file_max_size,
  169. backupCount=options.log_file_num_backups)
  170. elif rotate_mode == 'time':
  171. channel = logging.handlers.TimedRotatingFileHandler(
  172. filename=options.log_file_prefix,
  173. when=options.log_rotate_when,
  174. interval=options.log_rotate_interval,
  175. backupCount=options.log_file_num_backups)
  176. else:
  177. error_message = 'The value of log_rotate_mode option should be ' +\
  178. '"size" or "time", not "%s".' % rotate_mode
  179. raise ValueError(error_message)
  180. channel.setFormatter(LogFormatter(color=False))
  181. logger.addHandler(channel)
  182. if (options.log_to_stderr or
  183. (options.log_to_stderr is None and not logger.handlers)):
  184. # Set up color if we are in a tty and curses is installed
  185. channel = logging.StreamHandler()
  186. channel.setFormatter(LogFormatter())
  187. logger.addHandler(channel)
  188. def define_logging_options(options=None):
  189. """Add logging-related flags to ``options``.
  190. These options are present automatically on the default options instance;
  191. this method is only necessary if you have created your own `.OptionParser`.
  192. .. versionadded:: 4.2
  193. This function existed in prior versions but was broken and undocumented until 4.2.
  194. """
  195. if options is None:
  196. # late import to prevent cycle
  197. from tornado.options import options
  198. options.define("logging", default="info",
  199. help=("Set the Python log level. If 'none', tornado won't touch the "
  200. "logging configuration."),
  201. metavar="debug|info|warning|error|none")
  202. options.define("log_to_stderr", type=bool, default=None,
  203. help=("Send log output to stderr (colorized if possible). "
  204. "By default use stderr if --log_file_prefix is not set and "
  205. "no other logging is configured."))
  206. options.define("log_file_prefix", type=str, default=None, metavar="PATH",
  207. help=("Path prefix for log files. "
  208. "Note that if you are running multiple tornado processes, "
  209. "log_file_prefix must be different for each of them (e.g. "
  210. "include the port number)"))
  211. options.define("log_file_max_size", type=int, default=100 * 1000 * 1000,
  212. help="max size of log files before rollover")
  213. options.define("log_file_num_backups", type=int, default=10,
  214. help="number of log files to keep")
  215. options.define("log_rotate_when", type=str, default='midnight',
  216. help=("specify the type of TimedRotatingFileHandler interval "
  217. "other options:('S', 'M', 'H', 'D', 'W0'-'W6')"))
  218. options.define("log_rotate_interval", type=int, default=1,
  219. help="The interval value of timed rotating")
  220. options.define("log_rotate_mode", type=str, default='size',
  221. help="The mode of rotating files(time or size)")
  222. options.add_parse_callback(lambda: enable_pretty_logging(options))