test_log.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. from __future__ import absolute_import, unicode_literals
  2. import logging
  3. import pytest
  4. import sys
  5. from collections import defaultdict
  6. from io import StringIO
  7. from tempfile import mktemp
  8. from case import Mock, mock, patch, skip
  9. from case.utils import get_logger_handlers
  10. from celery import signals
  11. from celery import uuid
  12. from celery.app.log import TaskFormatter
  13. from celery.five import python_2_unicode_compatible
  14. from celery.utils.log import LoggingProxy
  15. from celery.utils.log import (
  16. get_logger,
  17. ColorFormatter,
  18. logger as base_logger,
  19. get_task_logger,
  20. task_logger,
  21. in_sighandler,
  22. logger_isa,
  23. )
  24. class test_TaskFormatter:
  25. def test_no_task(self):
  26. class Record(object):
  27. msg = 'hello world'
  28. levelname = 'info'
  29. exc_text = exc_info = None
  30. stack_info = None
  31. def getMessage(self):
  32. return self.msg
  33. record = Record()
  34. x = TaskFormatter()
  35. x.format(record)
  36. assert record.task_name == '???'
  37. assert record.task_id == '???'
  38. class test_logger_isa:
  39. def test_isa(self):
  40. x = get_task_logger('Z1george')
  41. assert logger_isa(x, task_logger)
  42. prev_x, x.parent = x.parent, None
  43. try:
  44. assert not logger_isa(x, task_logger)
  45. finally:
  46. x.parent = prev_x
  47. y = get_task_logger('Z1elaine')
  48. y.parent = x
  49. assert logger_isa(y, task_logger)
  50. assert logger_isa(y, x)
  51. assert logger_isa(y, y)
  52. z = get_task_logger('Z1jerry')
  53. z.parent = y
  54. assert logger_isa(z, task_logger)
  55. assert logger_isa(z, y)
  56. assert logger_isa(z, x)
  57. assert logger_isa(z, z)
  58. def test_recursive(self):
  59. x = get_task_logger('X1foo')
  60. prev, x.parent = x.parent, x
  61. try:
  62. with pytest.raises(RuntimeError):
  63. logger_isa(x, task_logger)
  64. finally:
  65. x.parent = prev
  66. y = get_task_logger('X2foo')
  67. z = get_task_logger('X2foo')
  68. prev_y, y.parent = y.parent, z
  69. try:
  70. prev_z, z.parent = z.parent, y
  71. try:
  72. with pytest.raises(RuntimeError):
  73. logger_isa(y, task_logger)
  74. finally:
  75. z.parent = prev_z
  76. finally:
  77. y.parent = prev_y
  78. class test_ColorFormatter:
  79. @patch('celery.utils.log.safe_str')
  80. @patch('logging.Formatter.formatException')
  81. def test_formatException_not_string(self, fe, safe_str):
  82. x = ColorFormatter()
  83. value = KeyError()
  84. fe.return_value = value
  85. assert x.formatException(value) is value
  86. fe.assert_called()
  87. safe_str.assert_not_called()
  88. @patch('logging.Formatter.formatException')
  89. @patch('celery.utils.log.safe_str')
  90. def test_formatException_bytes(self, safe_str, fe):
  91. x = ColorFormatter()
  92. fe.return_value = b'HELLO'
  93. try:
  94. raise Exception()
  95. except Exception:
  96. assert x.formatException(sys.exc_info())
  97. if sys.version_info[0] == 2:
  98. safe_str.assert_called()
  99. @patch('logging.Formatter.format')
  100. def test_format_object(self, _format):
  101. x = ColorFormatter()
  102. x.use_color = True
  103. record = Mock()
  104. record.levelname = 'ERROR'
  105. record.msg = object()
  106. assert x.format(record)
  107. @patch('celery.utils.log.safe_str')
  108. def test_format_raises(self, safe_str):
  109. x = ColorFormatter()
  110. def on_safe_str(s):
  111. try:
  112. raise ValueError('foo')
  113. finally:
  114. safe_str.side_effect = None
  115. safe_str.side_effect = on_safe_str
  116. @python_2_unicode_compatible
  117. class Record(object):
  118. levelname = 'ERROR'
  119. msg = 'HELLO'
  120. exc_info = 1
  121. exc_text = 'error text'
  122. stack_info = None
  123. def __str__(self):
  124. return on_safe_str('')
  125. def getMessage(self):
  126. return self.msg
  127. record = Record()
  128. safe_str.return_value = record
  129. msg = x.format(record)
  130. assert '<Unrepresentable' in msg
  131. assert safe_str.call_count == 1
  132. @skip.if_python3()
  133. @patch('celery.utils.log.safe_str')
  134. def test_format_raises_no_color(self, safe_str):
  135. x = ColorFormatter(use_color=False)
  136. record = Mock()
  137. record.levelname = 'ERROR'
  138. record.msg = 'HELLO'
  139. record.exc_text = 'error text'
  140. x.format(record)
  141. assert safe_str.call_count == 1
  142. class test_default_logger:
  143. def setup(self):
  144. self.setup_logger = self.app.log.setup_logger
  145. self.get_logger = lambda n=None: get_logger(n) if n else logging.root
  146. signals.setup_logging.receivers[:] = []
  147. self.app.log.already_setup = False
  148. def test_get_logger_sets_parent(self):
  149. logger = get_logger('celery.test_get_logger')
  150. assert logger.parent.name == base_logger.name
  151. def test_get_logger_root(self):
  152. logger = get_logger(base_logger.name)
  153. assert logger.parent is logging.root
  154. @mock.restore_logging()
  155. def test_setup_logging_subsystem_misc(self):
  156. self.app.log.setup_logging_subsystem(loglevel=None)
  157. @mock.restore_logging()
  158. def test_setup_logging_subsystem_misc2(self):
  159. self.app.conf.worker_hijack_root_logger = True
  160. self.app.log.setup_logging_subsystem()
  161. def test_get_default_logger(self):
  162. assert self.app.log.get_default_logger()
  163. def test_configure_logger(self):
  164. logger = self.app.log.get_default_logger()
  165. self.app.log._configure_logger(logger, sys.stderr, None, '', False)
  166. self.app.log._configure_logger(None, sys.stderr, None, '', False)
  167. logger.handlers[:] = []
  168. @mock.restore_logging()
  169. def test_setup_logging_subsystem_colorize(self):
  170. self.app.log.setup_logging_subsystem(colorize=None)
  171. self.app.log.setup_logging_subsystem(colorize=True)
  172. @mock.restore_logging()
  173. def test_setup_logging_subsystem_no_mputil(self):
  174. with mock.mask_modules('billiard.util'):
  175. self.app.log.setup_logging_subsystem()
  176. @mock.restore_logging()
  177. def test_setup_logger(self):
  178. logger = self.setup_logger(loglevel=logging.ERROR, logfile=None,
  179. root=False, colorize=True)
  180. logger.handlers = []
  181. self.app.log.already_setup = False
  182. logger = self.setup_logger(loglevel=logging.ERROR, logfile=None,
  183. root=False, colorize=None)
  184. # setup_logger logs to stderr without logfile argument.
  185. assert (get_logger_handlers(logger)[0].stream is
  186. sys.__stderr__)
  187. @mock.restore_logging()
  188. def test_setup_logger_no_handlers_stream(self):
  189. l = self.get_logger()
  190. l.handlers = []
  191. with mock.stdouts() as outs:
  192. stdout, stderr = outs
  193. l = self.setup_logger(logfile=sys.stderr,
  194. loglevel=logging.INFO, root=False)
  195. l.info('The quick brown fox...')
  196. assert 'The quick brown fox...' in stderr.getvalue()
  197. @patch('os.fstat')
  198. def test_setup_logger_no_handlers_file(self, *args):
  199. tempfile = mktemp(suffix='unittest', prefix='celery')
  200. _open = ('builtins.open' if sys.version_info[0] == 3
  201. else '__builtin__.open')
  202. with patch(_open) as osopen:
  203. with mock.restore_logging():
  204. files = defaultdict(StringIO)
  205. def open_file(filename, *args, **kwargs):
  206. f = files[filename]
  207. f.fileno = Mock()
  208. f.fileno.return_value = 99
  209. return f
  210. osopen.side_effect = open_file
  211. l = self.get_logger()
  212. l.handlers = []
  213. l = self.setup_logger(
  214. logfile=tempfile, loglevel=logging.INFO, root=False,
  215. )
  216. assert isinstance(get_logger_handlers(l)[0],
  217. logging.FileHandler)
  218. assert tempfile in files
  219. @mock.restore_logging()
  220. def test_redirect_stdouts(self):
  221. logger = self.setup_logger(loglevel=logging.ERROR, logfile=None,
  222. root=False)
  223. try:
  224. with mock.wrap_logger(logger) as sio:
  225. self.app.log.redirect_stdouts_to_logger(
  226. logger, loglevel=logging.ERROR,
  227. )
  228. logger.error('foo')
  229. assert 'foo' in sio.getvalue()
  230. self.app.log.redirect_stdouts_to_logger(
  231. logger, stdout=False, stderr=False,
  232. )
  233. finally:
  234. sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__
  235. @mock.restore_logging()
  236. def test_logging_proxy(self):
  237. logger = self.setup_logger(loglevel=logging.ERROR, logfile=None,
  238. root=False)
  239. with mock.wrap_logger(logger) as sio:
  240. p = LoggingProxy(logger, loglevel=logging.ERROR)
  241. p.close()
  242. p.write('foo')
  243. assert 'foo' not in sio.getvalue()
  244. p.closed = False
  245. p.write('foo')
  246. assert 'foo' in sio.getvalue()
  247. lines = ['baz', 'xuzzy']
  248. p.writelines(lines)
  249. for line in lines:
  250. assert line in sio.getvalue()
  251. p.flush()
  252. p.close()
  253. assert not p.isatty()
  254. with mock.stdouts() as (stdout, stderr):
  255. with in_sighandler():
  256. p.write('foo')
  257. assert stderr.getvalue()
  258. @mock.restore_logging()
  259. def test_logging_proxy_recurse_protection(self):
  260. logger = self.setup_logger(loglevel=logging.ERROR, logfile=None,
  261. root=False)
  262. p = LoggingProxy(logger, loglevel=logging.ERROR)
  263. p._thread.recurse_protection = True
  264. try:
  265. assert p.write('FOOFO') is None
  266. finally:
  267. p._thread.recurse_protection = False
  268. class test_task_logger(test_default_logger):
  269. def setup(self):
  270. logger = self.logger = get_logger('celery.task')
  271. logger.handlers = []
  272. logging.root.manager.loggerDict.pop(logger.name, None)
  273. self.uid = uuid()
  274. @self.app.task(shared=False)
  275. def test_task():
  276. pass
  277. self.get_logger().handlers = []
  278. self.task = test_task
  279. from celery._state import _task_stack
  280. _task_stack.push(test_task)
  281. def teardown(self):
  282. from celery._state import _task_stack
  283. _task_stack.pop()
  284. def setup_logger(self, *args, **kwargs):
  285. return self.app.log.setup_task_loggers(*args, **kwargs)
  286. def get_logger(self, *args, **kwargs):
  287. return get_task_logger('test_task_logger')
  288. def test_renaming_base_logger(self):
  289. with pytest.raises(RuntimeError):
  290. get_task_logger('celery')
  291. def test_renaming_task_logger(self):
  292. with pytest.raises(RuntimeError):
  293. get_task_logger('celery.task')
  294. class MockLogger(logging.Logger):
  295. _records = None
  296. def __init__(self, *args, **kwargs):
  297. self._records = []
  298. logging.Logger.__init__(self, *args, **kwargs)
  299. def handle(self, record):
  300. self._records.append(record)
  301. def isEnabledFor(self, level):
  302. return True