| 1 |
from sys import exc_info |
| 2 |
from traceback import format_exception |
| 3 |
from logging import ERROR, getLogger |
| 4 |
from ptrace.logging_tools import getLogFunc, changeLogLevel |
| 5 |
|
| 6 |
PTRACE_ERRORS = Exception |
| 7 |
|
| 8 |
|
| 9 |
def writeBacktrace(logger, log_level=ERROR): |
| 10 |
""" |
| 11 |
Write a backtrace into the logger with the specified log level. |
| 12 |
""" |
| 13 |
log_func = getLogFunc(logger, log_level) |
| 14 |
try: |
| 15 |
info = exc_info() |
| 16 |
trace = format_exception(*info) |
| 17 |
if trace[0] != "None\n": |
| 18 |
trace = ''.join(trace).rstrip() |
| 19 |
for line in trace.split("\n"): |
| 20 |
log_func(line.rstrip()) |
| 21 |
return |
| 22 |
except Exception: |
| 23 |
pass |
| 24 |
log_func("Unable to get backtrace") |
| 25 |
|
| 26 |
|
| 27 |
def formatError(error): |
| 28 |
""" |
| 29 |
Format an error as a string. Write the error type as prefix. |
| 30 |
Eg. "[ValueError] invalid value". |
| 31 |
""" |
| 32 |
return "[%s] %s" % (error.__class__.__name__, error) |
| 33 |
|
| 34 |
|
| 35 |
def writeError(logger, error, title="ERROR", log_level=ERROR): |
| 36 |
""" |
| 37 |
Write an error into the logger: |
| 38 |
- logger: the logger (if None, use getLogger()) |
| 39 |
- error: the exception object |
| 40 |
- title: error message prefix (e.g. title="Initialization error") |
| 41 |
- log_level: log level of the error |
| 42 |
|
| 43 |
If the exception is a SystemExit or a KeyboardInterrupt, re-emit |
| 44 |
(raise) the exception and don't write it. |
| 45 |
""" |
| 46 |
if not logger: |
| 47 |
logger = getLogger() |
| 48 |
if error.__class__ in (SystemExit, KeyboardInterrupt): |
| 49 |
raise error |
| 50 |
log_func = getLogFunc(logger, log_level) |
| 51 |
log_func("%s: %s" % (title, formatError(error))) |
| 52 |
writeBacktrace(logger, log_level=changeLogLevel(log_level, -1)) |
| 53 |
|
| 54 |
|
| 55 |
class PtraceError(Exception): |
| 56 |
""" |
| 57 |
Ptrace error: have the optional attributes errno and pid. |
| 58 |
""" |
| 59 |
|
| 60 |
def __init__(self, message, errno=None, pid=None): |
| 61 |
Exception.__init__(self, message) |
| 62 |
self.errno = errno |
| 63 |
self.pid = pid |