-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlogger.py
More file actions
143 lines (117 loc) · 4.56 KB
/
logger.py
File metadata and controls
143 lines (117 loc) · 4.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import os
import re
import sys
from logging import Logger
from typing import Any, Optional, Union
from loguru import logger
def format_logs(record):
end = record["extra"].get("end", "\n")
start = record["extra"].get("start", "")
return start + "<level>{message}</level>" + end
class LoggerMixin:
verbose: bool = os.environ.get("VECOREL_VERBOSE", "0") == "1"
logger: Optional[Logger] = None
def __init__(self):
if LoggerMixin.logger is None:
logger.remove()
LoggerMixin.logger = logger
LoggerMixin.logger.add(
sys.stdout,
colorize=True,
format=format_logs,
level="DEBUG" if self.verbose else "INFO",
)
def debug(self, message: str, **kwargs):
self.log(message, "debug", **kwargs)
def info(self, message: str, **kwargs):
self.log(message, "info", **kwargs)
def warning(self, message: str, **kwargs):
self.log(message, "warning", **kwargs)
def error(self, message: Union[Exception, str], **kwargs):
self.log(message, "error", **kwargs)
def success(self, message: str, **kwargs):
self.log(message, "success", **kwargs)
def log(
self,
message,
level: str = "info",
start="",
end="\n",
indent="",
color=None,
style="normal",
):
if not isinstance(message, str):
message = str(message)
# Escape XML/HTML tags etc. that look like loguru color directives
# The regexp is coming directly from the loguru source code, see
# https://github.com/Delgan/loguru/blob/master/loguru/_colorizer.py
message = re.sub(
r"(</?(?:[fb]g\s)?[^<>\s]*>)", r"\\\1", message, count=0, flags=re.IGNORECASE
)
# Handle indentation (including multiple lines)
message = self._indent_text(message, indent)
# Coloring and Styling
if color is not None:
message = f"<{color}>{message}</{color}>"
if style is not None:
message = f"<{style}>{message}</{style}>"
# Default template for the message
message = start + f"<level>{message}</level>" + end
# Log it
LoggerMixin.logger.opt(colors=True, raw=True).bind(start=start, end=end).log(
level.upper(), message
)
def exception(self, e: Exception):
LoggerMixin.logger.exception(e)
# strlen = -1 disables truncation
def print_pretty(self, data, depth=0, max_depth=1, strlen=50):
formatted = self._format_data(data, depth=depth, max_depth=max_depth, strlen=strlen).strip(
"\r\n"
)
LoggerMixin.logger.opt(colors=True, raw=True).log("INFO", f"<n>{formatted}</n>\n")
def _indent_text(self, text: str, indent: str) -> str:
indent2 = "\n" + " " * len(indent)
lines = text.splitlines()
return indent + indent2.join(lines)
def _format_data(self, value: Any, depth=0, max_depth=1, strlen=50):
if hasattr(value, "to_dict"):
value = value.to_dict()
output = ""
prefix = " " * depth
if isinstance(value, dict):
if depth <= max_depth:
if depth > 0:
output += "\n"
for key, value in value.items():
output += f"{prefix}<cyan>{key}</>: "
output += self._format_data(
value, depth=depth + 1, max_depth=max_depth, strlen=strlen
)
return output
else:
return f"<yellow>object (omitted, {len(value)} key/value pairs)</>\n"
elif isinstance(value, list):
if depth <= max_depth:
if depth > 0:
output += "\n"
for item in value:
output += f"{prefix}- "
output += self._format_data(
item, depth=depth + 1, max_depth=max_depth, strlen=strlen
)
return output
else:
return f"<yellow>array (omitted, {len(value)} elements)</>\n"
if not isinstance(value, str):
value = str(value)
length = len(value)
if strlen >= 0 and length > strlen:
output += value[:strlen]
if len(value) > strlen:
output += f"<yellow>... ({length - strlen} chars omitted)</>"
else:
output += value
if len(prefix) > 0:
output = self._indent_text(output, prefix).lstrip()
return output + "\n"