crashhandler.py 8.5 KB

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