log_test.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. #
  2. # Copyright 2012 Facebook
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. from __future__ import absolute_import, division, print_function
  16. import contextlib
  17. import glob
  18. import logging
  19. import os
  20. import re
  21. import subprocess
  22. import sys
  23. import tempfile
  24. import warnings
  25. from tornado.escape import utf8
  26. from tornado.log import LogFormatter, define_logging_options, enable_pretty_logging
  27. from tornado.options import OptionParser
  28. from tornado.test.util import unittest
  29. from tornado.util import basestring_type
  30. @contextlib.contextmanager
  31. def ignore_bytes_warning():
  32. with warnings.catch_warnings():
  33. warnings.simplefilter('ignore', category=BytesWarning)
  34. yield
  35. class LogFormatterTest(unittest.TestCase):
  36. # Matches the output of a single logging call (which may be multiple lines
  37. # if a traceback was included, so we use the DOTALL option)
  38. LINE_RE = re.compile(
  39. b"(?s)\x01\\[E [0-9]{6} [0-9]{2}:[0-9]{2}:[0-9]{2} log_test:[0-9]+\\]\x02 (.*)")
  40. def setUp(self):
  41. self.formatter = LogFormatter(color=False)
  42. # Fake color support. We can't guarantee anything about the $TERM
  43. # variable when the tests are run, so just patch in some values
  44. # for testing. (testing with color off fails to expose some potential
  45. # encoding issues from the control characters)
  46. self.formatter._colors = {
  47. logging.ERROR: u"\u0001",
  48. }
  49. self.formatter._normal = u"\u0002"
  50. # construct a Logger directly to bypass getLogger's caching
  51. self.logger = logging.Logger('LogFormatterTest')
  52. self.logger.propagate = False
  53. self.tempdir = tempfile.mkdtemp()
  54. self.filename = os.path.join(self.tempdir, 'log.out')
  55. self.handler = self.make_handler(self.filename)
  56. self.handler.setFormatter(self.formatter)
  57. self.logger.addHandler(self.handler)
  58. def tearDown(self):
  59. self.handler.close()
  60. os.unlink(self.filename)
  61. os.rmdir(self.tempdir)
  62. def make_handler(self, filename):
  63. # Base case: default setup without explicit encoding.
  64. # In python 2, supports arbitrary byte strings and unicode objects
  65. # that contain only ascii. In python 3, supports ascii-only unicode
  66. # strings (but byte strings will be repr'd automatically).
  67. return logging.FileHandler(filename)
  68. def get_output(self):
  69. with open(self.filename, "rb") as f:
  70. line = f.read().strip()
  71. m = LogFormatterTest.LINE_RE.match(line)
  72. if m:
  73. return m.group(1)
  74. else:
  75. raise Exception("output didn't match regex: %r" % line)
  76. def test_basic_logging(self):
  77. self.logger.error("foo")
  78. self.assertEqual(self.get_output(), b"foo")
  79. def test_bytes_logging(self):
  80. with ignore_bytes_warning():
  81. # This will be "\xe9" on python 2 or "b'\xe9'" on python 3
  82. self.logger.error(b"\xe9")
  83. self.assertEqual(self.get_output(), utf8(repr(b"\xe9")))
  84. def test_utf8_logging(self):
  85. with ignore_bytes_warning():
  86. self.logger.error(u"\u00e9".encode("utf8"))
  87. if issubclass(bytes, basestring_type):
  88. # on python 2, utf8 byte strings (and by extension ascii byte
  89. # strings) are passed through as-is.
  90. self.assertEqual(self.get_output(), utf8(u"\u00e9"))
  91. else:
  92. # on python 3, byte strings always get repr'd even if
  93. # they're ascii-only, so this degenerates into another
  94. # copy of test_bytes_logging.
  95. self.assertEqual(self.get_output(), utf8(repr(utf8(u"\u00e9"))))
  96. def test_bytes_exception_logging(self):
  97. try:
  98. raise Exception(b'\xe9')
  99. except Exception:
  100. self.logger.exception('caught exception')
  101. # This will be "Exception: \xe9" on python 2 or
  102. # "Exception: b'\xe9'" on python 3.
  103. output = self.get_output()
  104. self.assertRegexpMatches(output, br'Exception.*\\xe9')
  105. # The traceback contains newlines, which should not have been escaped.
  106. self.assertNotIn(br'\n', output)
  107. class UnicodeLogFormatterTest(LogFormatterTest):
  108. def make_handler(self, filename):
  109. # Adding an explicit encoding configuration allows non-ascii unicode
  110. # strings in both python 2 and 3, without changing the behavior
  111. # for byte strings.
  112. return logging.FileHandler(filename, encoding="utf8")
  113. def test_unicode_logging(self):
  114. self.logger.error(u"\u00e9")
  115. self.assertEqual(self.get_output(), utf8(u"\u00e9"))
  116. class EnablePrettyLoggingTest(unittest.TestCase):
  117. def setUp(self):
  118. super(EnablePrettyLoggingTest, self).setUp()
  119. self.options = OptionParser()
  120. define_logging_options(self.options)
  121. self.logger = logging.Logger('tornado.test.log_test.EnablePrettyLoggingTest')
  122. self.logger.propagate = False
  123. def test_log_file(self):
  124. tmpdir = tempfile.mkdtemp()
  125. try:
  126. self.options.log_file_prefix = tmpdir + '/test_log'
  127. enable_pretty_logging(options=self.options, logger=self.logger)
  128. self.assertEqual(1, len(self.logger.handlers))
  129. self.logger.error('hello')
  130. self.logger.handlers[0].flush()
  131. filenames = glob.glob(tmpdir + '/test_log*')
  132. self.assertEqual(1, len(filenames))
  133. with open(filenames[0]) as f:
  134. self.assertRegexpMatches(f.read(), r'^\[E [^]]*\] hello$')
  135. finally:
  136. for handler in self.logger.handlers:
  137. handler.flush()
  138. handler.close()
  139. for filename in glob.glob(tmpdir + '/test_log*'):
  140. os.unlink(filename)
  141. os.rmdir(tmpdir)
  142. def test_log_file_with_timed_rotating(self):
  143. tmpdir = tempfile.mkdtemp()
  144. try:
  145. self.options.log_file_prefix = tmpdir + '/test_log'
  146. self.options.log_rotate_mode = 'time'
  147. enable_pretty_logging(options=self.options, logger=self.logger)
  148. self.logger.error('hello')
  149. self.logger.handlers[0].flush()
  150. filenames = glob.glob(tmpdir + '/test_log*')
  151. self.assertEqual(1, len(filenames))
  152. with open(filenames[0]) as f:
  153. self.assertRegexpMatches(
  154. f.read(),
  155. r'^\[E [^]]*\] hello$')
  156. finally:
  157. for handler in self.logger.handlers:
  158. handler.flush()
  159. handler.close()
  160. for filename in glob.glob(tmpdir + '/test_log*'):
  161. os.unlink(filename)
  162. os.rmdir(tmpdir)
  163. def test_wrong_rotate_mode_value(self):
  164. try:
  165. self.options.log_file_prefix = 'some_path'
  166. self.options.log_rotate_mode = 'wrong_mode'
  167. self.assertRaises(ValueError, enable_pretty_logging,
  168. options=self.options, logger=self.logger)
  169. finally:
  170. for handler in self.logger.handlers:
  171. handler.flush()
  172. handler.close()
  173. class LoggingOptionTest(unittest.TestCase):
  174. """Test the ability to enable and disable Tornado's logging hooks."""
  175. def logs_present(self, statement, args=None):
  176. # Each test may manipulate and/or parse the options and then logs
  177. # a line at the 'info' level. This level is ignored in the
  178. # logging module by default, but Tornado turns it on by default
  179. # so it is the easiest way to tell whether tornado's logging hooks
  180. # ran.
  181. IMPORT = 'from tornado.options import options, parse_command_line'
  182. LOG_INFO = 'import logging; logging.info("hello")'
  183. program = ';'.join([IMPORT, statement, LOG_INFO])
  184. proc = subprocess.Popen(
  185. [sys.executable, '-c', program] + (args or []),
  186. stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  187. stdout, stderr = proc.communicate()
  188. self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)
  189. return b'hello' in stdout
  190. def test_default(self):
  191. self.assertFalse(self.logs_present('pass'))
  192. def test_tornado_default(self):
  193. self.assertTrue(self.logs_present('parse_command_line()'))
  194. def test_disable_command_line(self):
  195. self.assertFalse(self.logs_present('parse_command_line()',
  196. ['--logging=none']))
  197. def test_disable_command_line_case_insensitive(self):
  198. self.assertFalse(self.logs_present('parse_command_line()',
  199. ['--logging=None']))
  200. def test_disable_code_string(self):
  201. self.assertFalse(self.logs_present(
  202. 'options.logging = "none"; parse_command_line()'))
  203. def test_disable_code_none(self):
  204. self.assertFalse(self.logs_present(
  205. 'options.logging = None; parse_command_line()'))
  206. def test_disable_override(self):
  207. # command line trumps code defaults
  208. self.assertTrue(self.logs_present(
  209. 'options.logging = None; parse_command_line()',
  210. ['--logging=info']))