Coverage for /var/devmt/py/utils4_1.5.0rc1/utils4/reporterror.py: 100%
15 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-12 15:38 +0100
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-12 15:38 +0100
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3"""
4:Purpose: This module is designed to report program errors to the
5 console and/or a log file, using the :class:`~log.Log`
6 class.
8:Platform: Linux/Windows | Python 3.6+
9:Developer: J Berendt
10:Email: support@s3dev.uk
12:Comments: n/a
14:Example: For a usage example, refer to the :meth:`~reporterror` method's
15 docstring.
17"""
19import sys
20import traceback
21try:
22 from .log import Log
23except ImportError:
24 from utils4.log import Log
27if 'linux' in sys.platform.lower(): _PATH = '/tmp/reporterror.log'
28elif 'win' in sys.platform.lower(): _PATH = 'c:/temp/reporterror.log' # pragma: nocover
29else: _PATH = None # pragma: nocover
32def reporterror(error: Exception, logevent=False, logfilepath=_PATH):
33 """Report an error, derived from the passed ``Exception`` object.
35 Args:
36 error (Exception): Python ``Exception`` object from the built-in
37 try/except error handler. Refer to the use example below.
38 logevent (bool, optional): Send the error to a log file.
39 Defaults to False.
40 logfilename (str, optional): Full path to the log file. Defaults to:
42 - **Linux**: ``'/tmp/reporterror.log'``
43 - **Windows**: ``'c:/temp/reporterror.log'``
44 - **Other**: ``None``
46 Note:
47 The ``logevent`` parameter assumes the log file exists and the
48 header is already written.
50 For general logging help, you can use the :class:`~log.Log`
51 class which is built into ``utils4``.
53 :Example:
55 Report a simple error to the terminal::
57 >>> from utils4.reporterror import reporterror
59 >>> try:
60 >>> 1/0 # Force a known error.
61 >>> except Exception as err:
62 >>> reporterror(err)
64 Output::
66 ERROR: division by zero
67 TYPE: <class 'ZeroDivisionError'>
68 MODU: <./module/with/error.py>
69 FUNC: <func_name>
70 LINE: 2
71 CMD: 1/0
74 Report a simple error to the terminal and create a log file entry::
76 >>> from utils4.reporterror import reporterror
78 >>> try:
79 >>> 1/0 # Force a known error.
80 >>> except Exception as err:
81 >>> reporterror(err, logevent=True, logfilepath='/tmp/errors.log')
83 .. tip::
84 **Reminder:** The log file must already exist.
86 For help with the :mod:`utils4.log` module, please refer to the
87 documentation here: :class:`~log.Log`.
89 """
90 exc_type, _, exc_tb = sys.exc_info()
91 fnam, line, func, text = traceback.extract_tb(exc_tb)[-1]
92 msg = (f'\n'
93 f'ERROR:\t{error}\n'
94 f'TYPE:\t{exc_type}\n'
95 f'MODU:\t{fnam}\n'
96 f'FUNC:\t{func}\n'
97 f'LINE:\t{line}\n'
98 f'CMD:\t{text}\n')
99 print(msg)
100 if all([logevent, logfilepath]):
101 logger = Log(filepath=logfilepath, sep=',')
102 msg = f'ERROR: {error}; CMD: {text}; MODULE: {fnam}; FUNC: {func}; LINE: {line}'
103 logger.write(msg)
104 del (exc_type, exc_tb)