Coretex
log.py
1 # Copyright (C) 2023 Coretex LLC
2 
3 # This file is part of Coretex.ai
4 
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Affero General Public License for more details.
14 
15 # You should have received a copy of the GNU Affero General Public License
16 # along with this program. If not, see <https://www.gnu.org/licenses/>.
17 
18 from typing import Dict, Any, Tuple
19 from typing_extensions import Self
20 
21 import time
22 import json
23 
24 from .severity import LogSeverity
25 from .utils import colorMessage
26 from ..utils import mathematicalRound
27 
28 
29 class Log:
30 
31  """
32  Represents a single Coretex console log
33 
34  timestamp : float
35  timestamp of the log
36  message : str
37  message of the log
38  severity : LogSeverity
39  severity of the log
40  """
41 
42  def __init__(self, severity: LogSeverity, message: str) -> None:
43  self.timestamptimestamp = mathematicalRound(time.time(), 6)
44  self.severityseverity = severity
45  self.messagemessage = colorMessage(severity, message)
46 
47  def encode(self) -> Dict[str, Any]:
48  return {
49  "timestamp": self.timestamptimestamp,
50  "severity": self.severityseverity.value,
51  "content": self.messagemessage,
52  "type": 1 # Here for backwards compatibility
53  }
54 
55  @classmethod
56  def parse(cls, value: str) -> Tuple[Self, str]:
57  try:
58  jsonLog = json.loads(value)
59 
60  if not isinstance(jsonLog, dict):
61  raise ValueError
62 
63  if len(jsonLog) != 2:
64  raise ValueError
65 
66  return cls(LogSeverity(jsonLog["severity"]), jsonLog["message"].rstrip()), jsonLog["message"]
67  except:
68  return cls(LogSeverity.info, value.rstrip()), value