|
1 |
| -def info(string: str) -> None: |
2 |
| - print("[INFO] " + string) |
| 1 | +import json |
| 2 | +import sys |
| 3 | +from abc import abstractmethod, ABCMeta |
| 4 | +from typing import Self |
| 5 | + |
| 6 | +from termcolor import colored |
| 7 | + |
| 8 | +from cosmo.common import AbstractRecoverableError, JsonOutputType |
| 9 | +from cosmo.netbox_types import AbstractNetboxType |
| 10 | + |
| 11 | + |
| 12 | +class AbstractLogLevel(metaclass=ABCMeta): |
| 13 | + name: str = "abstract_log_level" |
| 14 | + def __str__(self): |
| 15 | + return self.name.upper() |
| 16 | + |
| 17 | +class InfoLogLevel(AbstractLogLevel): |
| 18 | + name = "info" |
| 19 | +class WarningLogLevel(AbstractLogLevel): |
| 20 | + name = "warning" |
| 21 | +class ErrorLogLevel(AbstractLogLevel): |
| 22 | + name = "error" |
| 23 | + |
| 24 | + |
| 25 | +O = object | AbstractNetboxType | None # object-being-logged-on type |
| 26 | +M = tuple[AbstractLogLevel, str, O] # message type |
| 27 | + |
| 28 | +class AbstractLoggingStrategy(metaclass=ABCMeta): |
| 29 | + @abstractmethod |
| 30 | + def flush(self): # this is for async and sync logging |
| 31 | + pass |
| 32 | + @abstractmethod |
| 33 | + def info(self, message: str, on: O): |
| 34 | + pass |
| 35 | + @abstractmethod |
| 36 | + def warn(self, message: str, on: O): |
| 37 | + pass |
| 38 | + @abstractmethod |
| 39 | + def error(self, message: str, on: O): |
| 40 | + pass |
| 41 | + @abstractmethod |
| 42 | + def exceptionHook(self, exception: type[BaseException], value: BaseException, traceback): |
| 43 | + pass |
| 44 | + |
| 45 | + |
| 46 | +class JsonLoggingStrategy(AbstractLoggingStrategy): |
| 47 | + info_queue: list[M] = [] |
| 48 | + warning_queue: list[M] = [] |
| 49 | + error_queue: list[M] = [] |
| 50 | + |
| 51 | + @staticmethod |
| 52 | + def _messageToJSON(m: M): |
| 53 | + log_level, message, obj = m |
| 54 | + return { |
| 55 | + "level": log_level.name, |
| 56 | + "message": message, |
| 57 | + "object": (obj.getMetaInfo().toJSON() if isinstance(obj, AbstractNetboxType) else { |
| 58 | + "type": type(obj).__name__, "value": str(obj) |
| 59 | + }), |
| 60 | + } |
| 61 | + |
| 62 | + def info(self, message: str, on: O): |
| 63 | + self.info_queue.append((InfoLogLevel(), message, on)) |
| 64 | + |
| 65 | + def warn(self, message: str, on: O): |
| 66 | + self.warning_queue.append((WarningLogLevel(), message, on)) |
| 67 | + |
| 68 | + def error(self, message: str, on: O): |
| 69 | + self.error_queue.append((ErrorLogLevel(), message, on)) |
| 70 | + |
| 71 | + def flush(self): |
| 72 | + # JSON-RPC like |
| 73 | + res = {} |
| 74 | + if len(self.warning_queue) + len(self.error_queue) == 0: |
| 75 | + res = { |
| 76 | + "result": list(map(self._messageToJSON, self.info_queue)), |
| 77 | + } |
| 78 | + else: |
| 79 | + res = { |
| 80 | + "error": list(map(self._messageToJSON, self.error_queue)), |
| 81 | + "warning": list(map(self._messageToJSON, self.warning_queue)), |
| 82 | + } |
| 83 | + print(json.dumps(res)) |
| 84 | + |
| 85 | + def exceptionHook(self, exception: type[BaseException], value: BaseException, traceback): |
| 86 | + if isinstance(exception, AbstractRecoverableError): |
| 87 | + self.warn(str(value), None) |
| 88 | + else: |
| 89 | + self.error(str(value), None) |
| 90 | + |
| 91 | + |
| 92 | +class HumanReadableLoggingStrategy(AbstractLoggingStrategy): |
| 93 | + def __init__(self, *args, netbox_instance_url: str, **kwargs): |
| 94 | + super().__init__(*args, **kwargs) |
| 95 | + self.nb_instance_url = netbox_instance_url |
| 96 | + |
| 97 | + def formatMessage(self, m: M) -> str: |
| 98 | + log_level, message, obj = m |
| 99 | + match log_level: |
| 100 | + case InfoLogLevel(): |
| 101 | + color = "blue" |
| 102 | + case WarningLogLevel(): |
| 103 | + color = "yellow" |
| 104 | + case ErrorLogLevel(): |
| 105 | + color = "red" |
| 106 | + case _: |
| 107 | + color = "white" |
| 108 | + log_level_colored = colored(log_level, color) |
| 109 | + default_log = f"[{log_level_colored}] {message}" |
| 110 | + match obj: |
| 111 | + case AbstractNetboxType(): |
| 112 | + meta_info = obj.getMetaInfo() |
| 113 | + full_url = meta_info.getFullObjectURL(self.nb_instance_url) |
| 114 | + return ( |
| 115 | + f"[{log_level_colored}]" |
| 116 | + f" [{meta_info.device_display_name.lower()}]" |
| 117 | + f" [{meta_info.display_name}] " |
| 118 | + f"{message}\n" + |
| 119 | + colored(f"🌐 {full_url}", "light_blue") |
| 120 | + ) |
| 121 | + case None: |
| 122 | + return default_log |
| 123 | + case str()|object(): |
| 124 | + return f"[{log_level_colored}] [{obj}] {message}" |
| 125 | + case _: |
| 126 | + return default_log |
| 127 | + |
| 128 | + def info(self, message: str, on: O): |
| 129 | + print(self.formatMessage((InfoLogLevel(), message, on))) |
| 130 | + |
| 131 | + def warn(self, message: str, on: O): |
| 132 | + print(self.formatMessage((WarningLogLevel(), message, on))) |
| 133 | + |
| 134 | + def error(self, message: str, on: O): |
| 135 | + print(self.formatMessage((ErrorLogLevel(), message, on))) |
| 136 | + |
| 137 | + def flush(self): |
| 138 | + pass |
| 139 | + |
| 140 | + def exceptionHook(self, exception: type[BaseException], value: BaseException, traceback): |
| 141 | + sys.__excepthook__(exception, value, traceback) |
| 142 | + |
| 143 | + |
| 144 | +class CosmoLogger: |
| 145 | + strategy: AbstractLoggingStrategy |
| 146 | + |
| 147 | + def setLoggingStrategy(self, strategy: AbstractLoggingStrategy) -> Self: |
| 148 | + self.strategy = strategy |
| 149 | + return self |
| 150 | + |
| 151 | + def flush(self) -> Self: |
| 152 | + self.strategy.flush() |
| 153 | + return self |
| 154 | + |
| 155 | + def getLoggingStrategy(self) -> AbstractLoggingStrategy: |
| 156 | + return self.strategy |
| 157 | + |
| 158 | + def info(self, message: str, on: O): |
| 159 | + self.strategy.info(message, on) |
| 160 | + |
| 161 | + def warn(self, message: str, on: O): |
| 162 | + self.strategy.warn(message, on) |
| 163 | + |
| 164 | + def error(self, message: str, on: O): |
| 165 | + self.strategy.error(message, on) |
| 166 | + |
| 167 | + def processHandledException(self, exception: BaseException): # for try/catch blocks to use |
| 168 | + self.exceptionHook(type(exception), exception, None, recovered=True) |
| 169 | + |
| 170 | + def exceptionHook(self, exception: type[BaseException], value: BaseException, traceback, recovered=False): |
| 171 | + self.strategy.exceptionHook(exception, value, traceback) |
| 172 | + if not recovered: |
| 173 | + # not recoverable because uncaught (we've been called from sys.excepthook, |
| 174 | + # since recovered is False by default). we're stopping the interpreter NOW. |
| 175 | + self.flush() |
| 176 | + |
| 177 | + |
| 178 | +def info(message: str, on: O = None) -> None: |
| 179 | + logger.info(message, on) |
| 180 | + |
| 181 | +def warn(message: str, on: O) -> None: |
| 182 | + logger.warn(message, on) |
| 183 | + |
| 184 | +def error(message: str, on:O) -> None: |
| 185 | + logger.error(message, on) |
| 186 | + |
| 187 | +logger = CosmoLogger() |
0 commit comments