test_log.py 11 KB

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