crashhandler.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. # encoding: utf-8
  2. """sys.excepthook for IPython itself, leaves a detailed report on disk.
  3. Authors:
  4. * Fernando Perez
  5. * Brian E. Granger
  6. """
  7. #-----------------------------------------------------------------------------
  8. # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
  9. # Copyright (C) 2008-2011 The IPython Development Team
  10. #
  11. # Distributed under the terms of the BSD License. The full license is in
  12. # the file COPYING, distributed as part of this software.
  13. #-----------------------------------------------------------------------------
  14. #-----------------------------------------------------------------------------
  15. # Imports
  16. #-----------------------------------------------------------------------------
  17. import sys
  18. import traceback
  19. from pprint import pformat
  20. from pathlib import Path
  21. from IPython.core import ultratb
  22. from IPython.core.release import author_email
  23. from IPython.utils.sysinfo import sys_info
  24. from IPython.utils.py3compat import input
  25. from IPython.core.release import __version__ as version
  26. from typing import Optional
  27. #-----------------------------------------------------------------------------
  28. # Code
  29. #-----------------------------------------------------------------------------
  30. # Template for the user message.
  31. _default_message_template = """\
  32. Oops, {app_name} crashed. We do our best to make it stable, but...
  33. A crash report was automatically generated with the following information:
  34. - A verbatim copy of the crash traceback.
  35. - A copy of your input history during this session.
  36. - Data on your current {app_name} configuration.
  37. It was left in the file named:
  38. \t'{crash_report_fname}'
  39. If you can email this file to the developers, the information in it will help
  40. them in understanding and correcting the problem.
  41. You can mail it to: {contact_name} at {contact_email}
  42. with the subject '{app_name} Crash Report'.
  43. If you want to do it now, the following command will work (under Unix):
  44. mail -s '{app_name} Crash Report' {contact_email} < {crash_report_fname}
  45. In your email, please also include information about:
  46. - The operating system under which the crash happened: Linux, macOS, Windows,
  47. other, and which exact version (for example: Ubuntu 16.04.3, macOS 10.13.2,
  48. Windows 10 Pro), and whether it is 32-bit or 64-bit;
  49. - How {app_name} was installed: using pip or conda, from GitHub, as part of
  50. a Docker container, or other, providing more detail if possible;
  51. - How to reproduce the crash: what exact sequence of instructions can one
  52. input to get the same crash? Ideally, find a minimal yet complete sequence
  53. of instructions that yields the crash.
  54. To ensure accurate tracking of this issue, please file a report about it at:
  55. {bug_tracker}
  56. """
  57. _lite_message_template = """
  58. If you suspect this is an IPython {version} bug, please report it at:
  59. https://github.com/ipython/ipython/issues
  60. or send an email to the mailing list at {email}
  61. You can print a more detailed traceback right now with "%tb", or use "%debug"
  62. to interactively debug it.
  63. Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
  64. {config}Application.verbose_crash=True
  65. """
  66. class CrashHandler(object):
  67. """Customizable crash handlers for IPython applications.
  68. Instances of this class provide a :meth:`__call__` method which can be
  69. used as a ``sys.excepthook``. The :meth:`__call__` signature is::
  70. def __call__(self, etype, evalue, etb)
  71. """
  72. message_template = _default_message_template
  73. section_sep = '\n\n'+'*'*75+'\n\n'
  74. def __init__(
  75. self,
  76. app,
  77. contact_name: Optional[str] = None,
  78. contact_email: Optional[str] = None,
  79. bug_tracker: Optional[str] = None,
  80. show_crash_traceback: bool = True,
  81. call_pdb: bool = False,
  82. ):
  83. """Create a new crash handler
  84. Parameters
  85. ----------
  86. app : Application
  87. A running :class:`Application` instance, which will be queried at
  88. crash time for internal information.
  89. contact_name : str
  90. A string with the name of the person to contact.
  91. contact_email : str
  92. A string with the email address of the contact.
  93. bug_tracker : str
  94. A string with the URL for your project's bug tracker.
  95. show_crash_traceback : bool
  96. If false, don't print the crash traceback on stderr, only generate
  97. the on-disk report
  98. call_pdb
  99. Whether to call pdb on crash
  100. Attributes
  101. ----------
  102. These instances contain some non-argument attributes which allow for
  103. further customization of the crash handler's behavior. Please see the
  104. source for further details.
  105. """
  106. self.crash_report_fname = "Crash_report_%s.txt" % app.name
  107. self.app = app
  108. self.call_pdb = call_pdb
  109. #self.call_pdb = True # dbg
  110. self.show_crash_traceback = show_crash_traceback
  111. self.info = dict(app_name = app.name,
  112. contact_name = contact_name,
  113. contact_email = contact_email,
  114. bug_tracker = bug_tracker,
  115. crash_report_fname = self.crash_report_fname)
  116. def __call__(self, etype, evalue, etb):
  117. """Handle an exception, call for compatible with sys.excepthook"""
  118. # do not allow the crash handler to be called twice without reinstalling it
  119. # this prevents unlikely errors in the crash handling from entering an
  120. # infinite loop.
  121. sys.excepthook = sys.__excepthook__
  122. # Report tracebacks shouldn't use color in general (safer for users)
  123. color_scheme = 'NoColor'
  124. # Use this ONLY for developer debugging (keep commented out for release)
  125. #color_scheme = 'Linux' # dbg
  126. try:
  127. rptdir = self.app.ipython_dir
  128. except:
  129. rptdir = Path.cwd()
  130. if rptdir is None or not Path.is_dir(rptdir):
  131. rptdir = Path.cwd()
  132. report_name = rptdir / self.crash_report_fname
  133. # write the report filename into the instance dict so it can get
  134. # properly expanded out in the user message template
  135. self.crash_report_fname = report_name
  136. self.info['crash_report_fname'] = report_name
  137. TBhandler = ultratb.VerboseTB(
  138. color_scheme=color_scheme,
  139. long_header=1,
  140. call_pdb=self.call_pdb,
  141. )
  142. if self.call_pdb:
  143. TBhandler(etype,evalue,etb)
  144. return
  145. else:
  146. traceback = TBhandler.text(etype,evalue,etb,context=31)
  147. # print traceback to screen
  148. if self.show_crash_traceback:
  149. print(traceback, file=sys.stderr)
  150. # and generate a complete report on disk
  151. try:
  152. report = open(report_name, "w", encoding="utf-8")
  153. except:
  154. print('Could not create crash report on disk.', file=sys.stderr)
  155. return
  156. with report:
  157. # Inform user on stderr of what happened
  158. print('\n'+'*'*70+'\n', file=sys.stderr)
  159. print(self.message_template.format(**self.info), file=sys.stderr)
  160. # Construct report on disk
  161. report.write(self.make_report(traceback))
  162. input("Hit <Enter> to quit (your terminal may close):")
  163. def make_report(self,traceback):
  164. """Return a string containing a crash report."""
  165. sec_sep = self.section_sep
  166. report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
  167. rpt_add = report.append
  168. rpt_add(sys_info())
  169. try:
  170. config = pformat(self.app.config)
  171. rpt_add(sec_sep)
  172. rpt_add('Application name: %s\n\n' % self.app_name)
  173. rpt_add('Current user configuration structure:\n\n')
  174. rpt_add(config)
  175. except:
  176. pass
  177. rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
  178. return ''.join(report)
  179. def crash_handler_lite(etype, evalue, tb):
  180. """a light excepthook, adding a small message to the usual traceback"""
  181. traceback.print_exception(etype, evalue, tb)
  182. from IPython.core.interactiveshell import InteractiveShell
  183. if InteractiveShell.initialized():
  184. # we are in a Shell environment, give %magic example
  185. config = "%config "
  186. else:
  187. # we are not in a shell, show generic config
  188. config = "c."
  189. print(_lite_message_template.format(email=author_email, config=config, version=version), file=sys.stderr)