|
| 1 | +"""Set of global and useful classes and functions used within the module. |
| 2 | +
|
| 3 | +:Exceptions: BOF-specific exceptions raised by the module. |
| 4 | +:Logging: Functions to enable or disable logging for the module. |
| 5 | +:JSON: JSON files handling (JSON is used for protocols specification). |
| 6 | +""" |
| 7 | + |
| 8 | +import logging |
| 9 | +import json |
| 10 | +from datetime import datetime |
| 11 | +from re import sub |
| 12 | + |
| 13 | +############################################################################### |
| 14 | +# BOF EXCEPTIONS # |
| 15 | +############################################################################### |
| 16 | + |
| 17 | +class BOFError(Exception): |
| 18 | + """Base class for all BOF exceptions. |
| 19 | +
|
| 20 | + .. warning:: Should not be used directly, please raise or catch subclasses |
| 21 | + instead. |
| 22 | + """ |
| 23 | + |
| 24 | +class BOFLibraryError(BOFError): |
| 25 | + """Library, files and import-related exceptions. |
| 26 | +
|
| 27 | + Usually raised when the library cannot find what it needs to work correctly |
| 28 | + (such as an external module or a file). |
| 29 | + """ |
| 30 | + pass |
| 31 | + |
| 32 | +class BOFNetworkError(BOFError): |
| 33 | + """Network-related exceptions. |
| 34 | +
|
| 35 | + Occurs when the network connection fails or is interrupted. |
| 36 | + """ |
| 37 | + pass |
| 38 | + |
| 39 | +class BOFProgrammingError(BOFError): |
| 40 | + """Script and module programming-related errors. |
| 41 | +
|
| 42 | + This occurs when a function or an argument is not used as expected. |
| 43 | +
|
| 44 | + .. note:: As a module user, this exception is the one that you may |
| 45 | + encounter the most. |
| 46 | + """ |
| 47 | + pass |
| 48 | + |
| 49 | +############################################################################### |
| 50 | +# BOF LOGGING # |
| 51 | +############################################################################### |
| 52 | + |
| 53 | +__DEFAULT_FILENAME = "bof" |
| 54 | +__LOG_SUFFIX = "log" |
| 55 | +__LOG_FORMAT = "%(asctime)s:%(levelname)s:%(message)s:%(filename)s:%(lineno)s" |
| 56 | + |
| 57 | +_LOGGING_ENABLED = False |
| 58 | + |
| 59 | +def enable_logging(filename:str="", error_only:bool=False) -> None: |
| 60 | + """Turn on logging features to store BOF-autogenerated events and user- |
| 61 | + generated events (call to ``bof.log()`` function). Relies on Python's |
| 62 | + ``logging`` module. |
| 63 | +
|
| 64 | + :param filename: Optional name of the file in which events will be saved. |
| 65 | + Default is ``bof.log``. |
| 66 | + :param error_only: All types of events are logged (info, warning, error) |
| 67 | + are saved unless this parameter is set to ``True``. |
| 68 | + """ |
| 69 | + level = logging.WARNING if error_only else logging.INFO |
| 70 | + filename = "{0}.{1}".format(filename if filename else __DEFAULT_FILENAME, |
| 71 | + __LOG_SUFFIX) |
| 72 | + logging.basicConfig(filename=filename, level=level, |
| 73 | + format=__LOG_FORMAT) |
| 74 | + now = datetime.now().strftime("%y%m%d-%H%M%S") |
| 75 | + logging.info("Starting BOF session {0}".format(now)) |
| 76 | + global _LOGGING_ENABLED |
| 77 | + _LOGGING_ENABLED = True |
| 78 | + |
| 79 | +def disable_logging() -> None: |
| 80 | + """Turn off logging features,""" |
| 81 | + global _LOGGING_ENABLED |
| 82 | + _LOGGING_ENABLED = False |
| 83 | + |
| 84 | +def log(message:str, level:str="INFO") -> bool: |
| 85 | + """Logs an event (``message``) to a file, if BOF logging is enabled |
| 86 | + (requires previous call to `bof.`enable_logging()``). A ``message`` is |
| 87 | + recorded along with event-related information: |
| 88 | +
|
| 89 | + - date and time |
| 90 | + - level (can be changed with parameter ``level``) |
| 91 | + - event location in the code (file name, line number) |
| 92 | +
|
| 93 | + :param message: Event definition. |
| 94 | + :param level: Type of event to record: ``ERROR``, ``WARNING``, ``DEBUG``. |
| 95 | + `INFO`` (default). Levels from Python's ``logging`` are used. |
| 96 | + :returns: Current state of logging (enabled/``True``, disabled/``False``). |
| 97 | + """ |
| 98 | + if _LOGGING_ENABLED: |
| 99 | + level = getattr(logging, level.upper()) |
| 100 | + if not isinstance(level, int): |
| 101 | + raise BOFProgrammingError("Invalid logging level") |
| 102 | + logging.log(level, message) |
| 103 | + return _LOGGING_ENABLED |
| 104 | + |
| 105 | +############################################################################### |
| 106 | +# BOF JSON FILE HANDLING # |
| 107 | +############################################################################### |
| 108 | + |
| 109 | +def load_json(filename:str) -> dict: |
| 110 | + """Loads a JSON file and returns the associated dictionary. |
| 111 | +
|
| 112 | + :raises BOFLibraryError: if the file cannot be opened. |
| 113 | + """ |
| 114 | + try: |
| 115 | + with open(filename, 'r') as jsonfile: |
| 116 | + return json.load(jsonfile) |
| 117 | + except Exception as e: |
| 118 | + raise BOFLibraryError("JSON File {0} cannot be used.".format(filename)) from None |
| 119 | + |
| 120 | +############################################################################### |
| 121 | +# STRING MANIPULATION # |
| 122 | +############################################################################### |
| 123 | + |
| 124 | +def to_property(value:str) -> str: |
| 125 | + """Replace all non alphanumeric characters in a string with ``_``""" |
| 126 | + return sub('[^0-9a-zA-Z]+', '_', value) |
0 commit comments