logging.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. # Copyright (c) 2009-2010 Google, Inc.
  2. # This program is free software; you can redistribute it and/or modify it under
  3. # the terms of the GNU General Public License as published by the Free Software
  4. # Foundation; either version 2 of the License, or (at your option) any later
  5. # version.
  6. #
  7. # This program is distributed in the hope that it will be useful, but WITHOUT
  8. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  10. #
  11. # You should have received a copy of the GNU General Public License along with
  12. # this program; if not, write to the Free Software Foundation, Inc.,
  13. # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  14. """checker for use of Python logging
  15. """
  16. from logilab import astng
  17. from pylint import checkers
  18. from pylint import interfaces
  19. from pylint.checkers import utils
  20. MSGS = {
  21. 'W1201': ('Specify string format arguments as logging function parameters',
  22. 'Used when a logging statement has a call form of '
  23. '"logging.<logging method>(format_string % (format_args...))". '
  24. 'Such calls should leave string interpolation to the logging '
  25. 'method itself and be written '
  26. '"logging.<logging method>(format_string, format_args...)" '
  27. 'so that the program may avoid incurring the cost of the '
  28. 'interpolation in those cases in which no message will be '
  29. 'logged. For more, see '
  30. 'http://www.python.org/dev/peps/pep-0282/.'),
  31. 'E1200': ('Unsupported logging format character %r (%#02x) at index %d',
  32. 'Used when an unsupported format character is used in a logging\
  33. statement format string.'),
  34. 'E1201': ('Logging format string ends in middle of conversion specifier',
  35. 'Used when a logging statement format string terminates before\
  36. the end of a conversion specifier.'),
  37. 'E1205': ('Too many arguments for logging format string',
  38. 'Used when a logging format string is given too few arguments.'),
  39. 'E1206': ('Not enough arguments for logging format string',
  40. 'Used when a logging format string is given too many arguments'),
  41. }
  42. CHECKED_CONVENIENCE_FUNCTIONS = set([
  43. 'critical', 'debug', 'error', 'exception', 'fatal', 'info', 'warn',
  44. 'warning'])
  45. class LoggingChecker(checkers.BaseChecker):
  46. """Checks use of the logging module."""
  47. __implements__ = interfaces.IASTNGChecker
  48. name = 'logging'
  49. msgs = MSGS
  50. def visit_module(self, unused_node):
  51. """Clears any state left in this checker from last module checked."""
  52. # The code being checked can just as easily "import logging as foo",
  53. # so it is necessary to process the imports and store in this field
  54. # what name the logging module is actually given.
  55. self._logging_name = None
  56. def visit_import(self, node):
  57. """Checks to see if this module uses Python's built-in logging."""
  58. for module, as_name in node.names:
  59. if module == 'logging':
  60. if as_name:
  61. self._logging_name = as_name
  62. else:
  63. self._logging_name = 'logging'
  64. def visit_callfunc(self, node):
  65. """Checks calls to (simple forms of) logging methods."""
  66. if (not isinstance(node.func, astng.Getattr)
  67. or not isinstance(node.func.expr, astng.Name)
  68. or node.func.expr.name != self._logging_name):
  69. return
  70. self._check_convenience_methods(node)
  71. self._check_log_methods(node)
  72. def _check_convenience_methods(self, node):
  73. """Checks calls to logging convenience methods (like logging.warn)."""
  74. if node.func.attrname not in CHECKED_CONVENIENCE_FUNCTIONS:
  75. return
  76. if node.starargs or node.kwargs or not node.args:
  77. # Either no args, star args, or double-star args. Beyond the
  78. # scope of this checker.
  79. return
  80. if isinstance(node.args[0], astng.BinOp) and node.args[0].op == '%':
  81. self.add_message('W1201', node=node)
  82. elif isinstance(node.args[0], astng.Const):
  83. self._check_format_string(node, 0)
  84. def _check_log_methods(self, node):
  85. """Checks calls to logging.log(level, format, *format_args)."""
  86. if node.func.attrname != 'log':
  87. return
  88. if node.starargs or node.kwargs or len(node.args) < 2:
  89. # Either a malformed call, star args, or double-star args. Beyond
  90. # the scope of this checker.
  91. return
  92. if isinstance(node.args[1], astng.BinOp) and node.args[1].op == '%':
  93. self.add_message('W1201', node=node)
  94. elif isinstance(node.args[1], astng.Const):
  95. self._check_format_string(node, 1)
  96. def _check_format_string(self, node, format_arg):
  97. """Checks that format string tokens match the supplied arguments.
  98. Args:
  99. node: AST node to be checked.
  100. format_arg: Index of the format string in the node arguments.
  101. """
  102. num_args = self._count_supplied_tokens(node.args[format_arg + 1:])
  103. if not num_args:
  104. # If no args were supplied, then all format strings are valid -
  105. # don't check any further.
  106. return
  107. format_string = node.args[format_arg].value
  108. if not isinstance(format_string, basestring):
  109. # If the log format is constant non-string (e.g. logging.debug(5)),
  110. # ensure there are no arguments.
  111. required_num_args = 0
  112. else:
  113. try:
  114. keyword_args, required_num_args = \
  115. utils.parse_format_string(format_string)
  116. if keyword_args:
  117. # Keyword checking on logging strings is complicated by
  118. # special keywords - out of scope.
  119. return
  120. except utils.UnsupportedFormatCharacter, e:
  121. c = format_string[e.index]
  122. self.add_message('E1200', node=node, args=(c, ord(c), e.index))
  123. return
  124. except utils.IncompleteFormatString:
  125. self.add_message('E1201', node=node)
  126. return
  127. if num_args > required_num_args:
  128. self.add_message('E1205', node=node)
  129. elif num_args < required_num_args:
  130. self.add_message('E1206', node=node)
  131. def _count_supplied_tokens(self, args):
  132. """Counts the number of tokens in an args list.
  133. The Python log functions allow for special keyword arguments: func,
  134. exc_info and extra. To handle these cases correctly, we only count
  135. arguments that aren't keywords.
  136. Args:
  137. args: List of AST nodes that are arguments for a log format string.
  138. Returns:
  139. Number of AST nodes that aren't keywords.
  140. """
  141. return sum(1 for arg in args if not isinstance(arg, astng.Keyword))
  142. def register(linter):
  143. """Required method to auto-register this checker."""
  144. linter.register_checker(LoggingChecker(linter))