test_log.py 11 KB

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