understand-py 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
understand/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ __version__ = "0.1.0"
2
+
3
+ from .collector import DataCollector
4
+ from .config import UnderstandConfig
5
+ from .encoder import ExceptionEncoder
6
+ from .fields import FieldProvider, RequestContext
7
+ from .handlers import AsyncHandler, BaseHandler, CallbackHandler, SyncHandler
8
+ from .logger import UnderstandLogger
9
+ from .tokens import TokenProvider
10
+
11
+ __all__ = [
12
+ "AsyncHandler",
13
+ "BaseHandler",
14
+ "CallbackHandler",
15
+ "DataCollector",
16
+ "ExceptionEncoder",
17
+ "FieldProvider",
18
+ "RequestContext",
19
+ "SyncHandler",
20
+ "TokenProvider",
21
+ "UnderstandConfig",
22
+ "UnderstandLogger",
23
+ "__version__",
24
+ ]
@@ -0,0 +1,27 @@
1
+ from typing import Any, Dict, List, Optional
2
+
3
+
4
+ class DataCollector:
5
+ def __init__(self, limit: int = 50) -> None:
6
+ self._data: Dict[str, Any] = {}
7
+ self.limit = limit
8
+
9
+ def set_limit(self, limit: int) -> None:
10
+ self.limit = limit
11
+
12
+ def reset(self) -> None:
13
+ self._data = {}
14
+
15
+ def set(self, key: str, value: Any) -> None:
16
+ self._data[key] = value
17
+
18
+ def set_in_array(self, key: str, value: Any) -> None:
19
+ values: List[Any] = list(self._data.get(key, []))
20
+ if len(values) > self.limit - 1:
21
+ values.pop(0)
22
+ values.append(value)
23
+ self._data[key] = values
24
+
25
+ def get_by_key(self, key: str) -> Optional[Any]:
26
+ return self._data.get(key)
27
+
understand/config.py ADDED
@@ -0,0 +1,82 @@
1
+ from dataclasses import dataclass, field
2
+ import os
3
+ from pathlib import Path
4
+ from typing import Callable, Optional, Sequence, Tuple
5
+
6
+
7
+ DEFAULT_HIDDEN_FIELDS = (
8
+ "password",
9
+ "password_confirmation",
10
+ "access_token",
11
+ "secret_key",
12
+ "token",
13
+ "access_key",
14
+ )
15
+
16
+
17
+ def _parse_bool(value: Optional[str], default: bool) -> bool:
18
+ if value is None:
19
+ return default
20
+
21
+ normalized = value.strip().lower()
22
+ if normalized in {"1", "true", "yes", "y", "on"}:
23
+ return True
24
+ if normalized in {"0", "false", "no", "n", "off"}:
25
+ return False
26
+ return default
27
+
28
+
29
+ def _parse_csv(value: Optional[str], default: Sequence[str]) -> Tuple[str, ...]:
30
+ if value is None:
31
+ return tuple(default)
32
+
33
+ return tuple(part.strip() for part in value.split(",") if part.strip())
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class UnderstandConfig:
38
+ token: Optional[str] = None
39
+ enabled: bool = True
40
+ api_url: str = "https://api.understand.io"
41
+ handler: str = "sync"
42
+ project_root: Path = field(default_factory=Path.cwd)
43
+ environment: Optional[str] = None
44
+ sql_enabled: bool = True
45
+ sql_bindings: bool = False
46
+ query_string_enabled: bool = True
47
+ request_body_enabled: bool = True
48
+ hidden_fields: Tuple[str, ...] = DEFAULT_HIDDEN_FIELDS
49
+ ignored_logs: Tuple[str, ...] = ()
50
+ log_filter: Optional[Callable[[str, object, object], bool]] = None
51
+ timeout: float = 5.0
52
+ stack_trace_limit: int = 100
53
+ ssl_ca_bundle: Optional[str] = None
54
+
55
+ def __post_init__(self) -> None:
56
+ object.__setattr__(self, "project_root", Path(self.project_root))
57
+ object.__setattr__(self, "hidden_fields", tuple(self.hidden_fields))
58
+ object.__setattr__(self, "ignored_logs", tuple(self.ignored_logs))
59
+
60
+ @classmethod
61
+ def from_env(cls, project_root: Optional[Path] = None) -> "UnderstandConfig":
62
+ request_body_value = os.environ.get("UNDERSTAND_REQUEST_BODY")
63
+ if request_body_value is None:
64
+ request_body_value = os.environ.get("UNDERSTAND_POST_DATA")
65
+
66
+ return cls(
67
+ token=os.environ.get("UNDERSTAND_TOKEN"),
68
+ enabled=_parse_bool(os.environ.get("UNDERSTAND_ENABLED"), True),
69
+ api_url=os.environ.get("UNDERSTAND_API_URL", "https://api.understand.io"),
70
+ handler=os.environ.get("UNDERSTAND_HANDLER", "sync"),
71
+ project_root=project_root if project_root is not None else Path.cwd(),
72
+ environment=os.environ.get("UNDERSTAND_ENV"),
73
+ sql_enabled=_parse_bool(os.environ.get("UNDERSTAND_SQL"), True),
74
+ sql_bindings=_parse_bool(os.environ.get("UNDERSTAND_SQL_BINDINGS"), False),
75
+ query_string_enabled=_parse_bool(os.environ.get("UNDERSTAND_QUERY_STRING"), True),
76
+ request_body_enabled=_parse_bool(request_body_value, True),
77
+ hidden_fields=_parse_csv(
78
+ os.environ.get("UNDERSTAND_HIDDEN_REQUEST_FIELDS"),
79
+ DEFAULT_HIDDEN_FIELDS,
80
+ ),
81
+ ssl_ca_bundle=os.environ.get("UNDERSTAND_SSL_CA_BUNDLE"),
82
+ )
understand/encoder.py ADDED
@@ -0,0 +1,96 @@
1
+ import inspect
2
+ from pathlib import Path
3
+ import traceback
4
+ from types import TracebackType
5
+ from typing import Any, Dict, Iterable, List, Optional
6
+
7
+ from .config import UnderstandConfig
8
+
9
+
10
+ class ExceptionEncoder:
11
+ def __init__(self, config: Optional[UnderstandConfig] = None) -> None:
12
+ self.config = config or UnderstandConfig()
13
+
14
+ def exception_to_dict(self, exception: BaseException) -> Dict[str, Any]:
15
+ if not isinstance(exception, BaseException):
16
+ raise TypeError("exception must be an instance of BaseException")
17
+
18
+ frames = self._traceback_to_frames(exception.__traceback__)
19
+ top = frames[-1] if frames else None
20
+ file_name = self._relative_path(top.filename) if top else None
21
+ line = top.lineno if top else None
22
+ class_name = exception.__class__.__name__
23
+ message = str(exception) if str(exception) else class_name
24
+
25
+ return {
26
+ "message": message,
27
+ "class": class_name,
28
+ "code": getattr(exception, "errno", None),
29
+ "file": file_name,
30
+ "line": line,
31
+ "stack": self.stack_trace_to_list(frames),
32
+ }
33
+
34
+ def set_current_stack_trace(self, error_log: Dict[str, Any]) -> Dict[str, Any]:
35
+ frames = [
36
+ frame
37
+ for frame in inspect.stack()[1 : self.config.stack_trace_limit + 1]
38
+ if "/understand/" not in frame.filename.replace("\\", "/")
39
+ ]
40
+ stack = self.stack_trace_to_list(frames)
41
+ if stack:
42
+ error_log["class"] = None
43
+ error_log["file"] = stack[0]["file"]
44
+ error_log["line"] = stack[0]["line"]
45
+ error_log["stack"] = stack
46
+ return error_log
47
+
48
+ def stack_trace_to_list(self, frames: Iterable[Any]) -> List[Dict[str, Any]]:
49
+ stack = []
50
+ for frame in list(frames)[-self.config.stack_trace_limit :]:
51
+ filename = getattr(frame, "filename", None)
52
+ lineno = getattr(frame, "lineno", None)
53
+ function = getattr(frame, "name", None) or getattr(frame, "function", None)
54
+ relative = self._relative_path(filename) if filename else None
55
+ stack.append(
56
+ {
57
+ "class": None,
58
+ "function": function,
59
+ "args": [],
60
+ "type": "function",
61
+ "file": relative,
62
+ "line": lineno,
63
+ "code": self.get_code(relative, lineno),
64
+ }
65
+ )
66
+ return stack
67
+
68
+ def get_code(self, relative_path: Optional[str], line: Optional[int], lines_around: int = 6) -> Optional[List[Dict[str, Any]]]:
69
+ if not relative_path or not line:
70
+ return None
71
+
72
+ path = self.config.project_root / relative_path
73
+ try:
74
+ lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
75
+ except OSError:
76
+ return None
77
+
78
+ start = max(1, line - lines_around)
79
+ end = min(len(lines), line + lines_around)
80
+ return [{"line": number, "code": lines[number - 1][:250].rstrip()} for number in range(start, end + 1)]
81
+
82
+ def _traceback_to_frames(self, tb: Optional[TracebackType]) -> List[traceback.FrameSummary]:
83
+ if tb is None:
84
+ return []
85
+ return traceback.extract_tb(tb)
86
+
87
+ def _relative_path(self, filename: Optional[str]) -> Optional[str]:
88
+ if filename is None:
89
+ return None
90
+
91
+ path = Path(filename)
92
+ try:
93
+ return str(path.resolve().relative_to(self.config.project_root.resolve()))
94
+ except ValueError:
95
+ return str(path)
96
+
understand/fields.py ADDED
@@ -0,0 +1,210 @@
1
+ from dataclasses import dataclass, field
2
+ from datetime import datetime
3
+ import hashlib
4
+ import platform
5
+ import sys
6
+ from typing import Any, Callable, Dict, Mapping, Optional
7
+
8
+ from .collector import DataCollector
9
+ from .config import UnderstandConfig
10
+ from .tokens import TokenProvider
11
+
12
+
13
+ @dataclass
14
+ class RequestContext:
15
+ path: Optional[str] = None
16
+ method: Optional[str] = None
17
+ query: Mapping[str, Any] = field(default_factory=dict)
18
+ body: Mapping[str, Any] = field(default_factory=dict)
19
+ client_ip: Optional[str] = None
20
+ server_ip: Optional[str] = None
21
+ user_agent: Optional[str] = None
22
+ host: Optional[str] = None
23
+ origin: Optional[str] = None
24
+ session_id: Optional[str] = None
25
+ session: Mapping[str, Any] = field(default_factory=dict)
26
+ user_id: Optional[Any] = None
27
+ route_name: Optional[str] = None
28
+
29
+
30
+ class FieldProvider:
31
+ def __init__(
32
+ self,
33
+ config: Optional[UnderstandConfig] = None,
34
+ token_provider: Optional[TokenProvider] = None,
35
+ data_collector: Optional[DataCollector] = None,
36
+ ) -> None:
37
+ self.config = config or UnderstandConfig()
38
+ self.token_provider = token_provider or TokenProvider()
39
+ self.data_collector = data_collector or DataCollector()
40
+ self.request_context: Optional[RequestContext] = None
41
+ self._providers: Dict[str, Callable[..., Any]] = {}
42
+
43
+ def extend(self, name: str, provider: Callable[..., Any]) -> None:
44
+ self._providers[name] = provider
45
+
46
+ def __getattr__(self, name: str) -> Any:
47
+ if name in self._providers:
48
+ return self._providers[name]
49
+ raise AttributeError(name)
50
+
51
+ def set_request_context(self, request_context: Optional[RequestContext]) -> None:
52
+ self.request_context = request_context
53
+
54
+ def resolve_values(
55
+ self,
56
+ callbacks: Mapping[str, Callable[[Mapping[str, Any]], Any]],
57
+ log: Mapping[str, Any],
58
+ ) -> Dict[str, Any]:
59
+ data: Dict[str, Any] = {}
60
+ for field_name, callback in callbacks.items():
61
+ try:
62
+ data[field_name] = callback(log)
63
+ except Exception:
64
+ data[field_name] = None
65
+ return data
66
+
67
+ def get_session_id(self, _log: Optional[Mapping[str, Any]] = None) -> Optional[str]:
68
+ if not self.request_context or not self.request_context.session_id:
69
+ return None
70
+ return hashlib.sha1(self.request_context.session_id.encode("utf-8")).hexdigest()
71
+
72
+ def get_request_id(self, _log: Optional[Mapping[str, Any]] = None) -> str:
73
+ return self.token_provider.get_token()
74
+
75
+ def get_process_identifier(self, _log: Optional[Mapping[str, Any]] = None) -> str:
76
+ return self.get_request_id()
77
+
78
+ def get_user_id(self, _log: Optional[Mapping[str, Any]] = None) -> Optional[Any]:
79
+ if not self.request_context:
80
+ return None
81
+ return self.request_context.user_id
82
+
83
+ def get_environment(self, _log: Optional[Mapping[str, Any]] = None) -> Optional[str]:
84
+ return self.config.environment
85
+
86
+ def get_url(self, _log: Optional[Mapping[str, Any]] = None) -> Optional[str]:
87
+ if not self.request_context or self.request_context.path is None:
88
+ return None
89
+ path = self.request_context.path
90
+ return path if path.startswith("/") else "/" + path
91
+
92
+ def get_request_method(self, _log: Optional[Mapping[str, Any]] = None) -> Optional[str]:
93
+ if not self.request_context:
94
+ return None
95
+ return self.request_context.method
96
+
97
+ def get_route_name(self, _log: Optional[Mapping[str, Any]] = None) -> Optional[str]:
98
+ if not self.request_context:
99
+ return None
100
+ return self.request_context.route_name
101
+
102
+ def get_from_session(self, key: str) -> Optional[Any]:
103
+ if not self.request_context:
104
+ return None
105
+ return self.request_context.session.get(key)
106
+
107
+ def get_query_string_array(self, _log: Optional[Mapping[str, Any]] = None) -> Optional[Dict[str, Any]]:
108
+ if not self.config.query_string_enabled:
109
+ return None
110
+ if not self.request_context:
111
+ return None
112
+ return self._parse_request_mapping(self.request_context.query)
113
+
114
+ def get_request_body_data(self, _log: Optional[Mapping[str, Any]] = None) -> Optional[Dict[str, Any]]:
115
+ if not self.config.request_body_enabled:
116
+ return None
117
+ if not self.request_context:
118
+ return None
119
+ if self.request_context.method and self.request_context.method.upper() in {"GET", "HEAD"}:
120
+ return None
121
+ return self._parse_request_mapping(self.request_context.body)
122
+
123
+ def get_post_data_array(self, log: Optional[Mapping[str, Any]] = None) -> Optional[Dict[str, Any]]:
124
+ return self.get_request_body_data(log)
125
+
126
+ def get_client_ip(self, _log: Optional[Mapping[str, Any]] = None) -> Optional[str]:
127
+ return self.request_context.client_ip if self.request_context else None
128
+
129
+ def get_server_ip(self, _log: Optional[Mapping[str, Any]] = None) -> Optional[str]:
130
+ return self.request_context.server_ip if self.request_context else None
131
+
132
+ def get_client_user_agent(self, _log: Optional[Mapping[str, Any]] = None) -> Optional[str]:
133
+ return self.request_context.user_agent if self.request_context else None
134
+
135
+ def get_host(self, _log: Optional[Mapping[str, Any]] = None) -> Optional[str]:
136
+ return self.request_context.host if self.request_context else None
137
+
138
+ def get_origin(self, _log: Optional[Mapping[str, Any]] = None) -> Optional[str]:
139
+ return self.request_context.origin if self.request_context else None
140
+
141
+ def get_python_version(self, _log: Optional[Mapping[str, Any]] = None) -> str:
142
+ return platform.python_version()
143
+
144
+ def get_logger_version(self, _log: Optional[Mapping[str, Any]] = None) -> str:
145
+ from . import __version__
146
+
147
+ return __version__
148
+
149
+ def get_console(self, _log: Optional[Mapping[str, Any]] = None) -> bool:
150
+ return True
151
+
152
+ def get_command(self, _log: Optional[Mapping[str, Any]] = None) -> Optional[str]:
153
+ return " ".join(sys.argv) if sys.argv else None
154
+
155
+ def get_artisan_command_name(self, log: Optional[Mapping[str, Any]] = None) -> Optional[str]:
156
+ return self.get_command(log)
157
+
158
+ def get_sql_queries(self, _log: Optional[Mapping[str, Any]] = None) -> Optional[Any]:
159
+ if not self.config.sql_enabled:
160
+ return None
161
+ queries = self.data_collector.get_by_key("sql_queries")
162
+ if not queries:
163
+ return None
164
+
165
+ result = []
166
+ for query in queries:
167
+ query_dict = dict(query)
168
+ bindings = list(query_dict.pop("bindings", []))
169
+ if self.config.sql_bindings:
170
+ query_dict["query"] = self._merge_bindings(str(query_dict.get("query", "")), bindings)
171
+ result.append(query_dict)
172
+ return result
173
+
174
+ def get_group_id(self, log: Mapping[str, Any]) -> str:
175
+ parts = []
176
+ for field_name in ("class", "file", "line", "code"):
177
+ value = log.get(field_name)
178
+ if field_name == "code" and (not value or value == "0"):
179
+ continue
180
+ parts.append("" if value is None else str(value))
181
+ return hashlib.sha1("#".join(parts).encode("utf-8")).hexdigest()
182
+
183
+ def _parse_request_mapping(self, mapping: Mapping[str, Any]) -> Dict[str, Any]:
184
+ parsed: Dict[str, Any] = {}
185
+ for key, value in mapping.items():
186
+ try:
187
+ parsed[key] = self._parse_request_field_value(key, value)
188
+ except Exception:
189
+ parsed[key] = "[handler error]"
190
+ return parsed
191
+
192
+ def _parse_request_field_value(self, key: str, value: Any) -> Any:
193
+ if key in self.config.hidden_fields:
194
+ return "[value hidden]"
195
+ if isinstance(value, (str, int, float, bool)) or value is None:
196
+ return value
197
+ if isinstance(value, (list, tuple, dict, set)):
198
+ return repr(value)
199
+ return value.__class__.__name__
200
+
201
+ def _merge_bindings(self, query: str, bindings: Any) -> str:
202
+ for value in bindings:
203
+ if isinstance(value, datetime):
204
+ binding = value.strftime("%Y-%m-%d %H:%M:%S")
205
+ elif isinstance(value, bool):
206
+ binding = "1" if value else "0"
207
+ else:
208
+ binding = str(value)
209
+ query = query.replace("?", binding, 1)
210
+ return query
understand/handlers.py ADDED
@@ -0,0 +1,69 @@
1
+ import json
2
+ import subprocess
3
+ from typing import Any, Callable, Dict, Optional
4
+ from urllib import request
5
+
6
+ from .config import UnderstandConfig
7
+
8
+
9
+ class BaseHandler:
10
+ def __init__(self, config: Optional[UnderstandConfig] = None) -> None:
11
+ self.config = config or UnderstandConfig()
12
+
13
+ def handle(self, request_data: Dict[str, Any]) -> Any:
14
+ payload = json.dumps(request_data, default=str)
15
+ response = self.send(payload)
16
+ return self.parse_response(response)
17
+
18
+ def send(self, data: str) -> Optional[str]:
19
+ raise NotImplementedError
20
+
21
+ def get_endpoint(self) -> str:
22
+ return "/".join([self.config.api_url.rstrip("/"), str(self.config.token or "")])
23
+
24
+ def parse_response(self, response: Optional[str]) -> Any:
25
+ if response is None:
26
+ return None
27
+ if response == "":
28
+ return None
29
+ return json.loads(response)
30
+
31
+
32
+ class SyncHandler(BaseHandler):
33
+ def send(self, data: str) -> Optional[str]:
34
+ req = request.Request(
35
+ self.get_endpoint(),
36
+ data=data.encode("utf-8"),
37
+ method="POST",
38
+ headers={
39
+ "Content-Type": "application/json",
40
+ "User-Agent": "Understand Python SDK.",
41
+ },
42
+ )
43
+ kwargs = {"timeout": self.config.timeout}
44
+ if self.config.ssl_ca_bundle:
45
+ kwargs["cafile"] = self.config.ssl_ca_bundle
46
+ with request.urlopen(req, **kwargs) as response:
47
+ return response.read().decode("utf-8")
48
+
49
+
50
+ class AsyncHandler(BaseHandler):
51
+ def send(self, data: str) -> None:
52
+ if len(data) >= 2_000_000:
53
+ return None
54
+
55
+ subprocess.Popen(
56
+ ["curl", "-X", "POST", "-d", data, self.get_endpoint()],
57
+ stdout=subprocess.DEVNULL,
58
+ stderr=subprocess.DEVNULL,
59
+ )
60
+ return None
61
+
62
+
63
+ class CallbackHandler(BaseHandler):
64
+ def __init__(self, callback: Callable[[str], Optional[str]], config: Optional[UnderstandConfig] = None) -> None:
65
+ super().__init__(config)
66
+ self.callback = callback
67
+
68
+ def send(self, data: str) -> Optional[str]:
69
+ return self.callback(data)
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,35 @@
1
+ import logging
2
+ import sys
3
+ from typing import Optional
4
+
5
+ from ..config import UnderstandConfig
6
+ from ..logger import UnderstandLogger
7
+
8
+
9
+ class UnderstandLoggingHandler(logging.Handler):
10
+ def __init__(self, understand_logger: UnderstandLogger, level: int = logging.NOTSET) -> None:
11
+ super().__init__(level)
12
+ self.understand_logger = understand_logger
13
+
14
+ @classmethod
15
+ def from_config(cls, config: Optional[UnderstandConfig] = None) -> "UnderstandLoggingHandler":
16
+ return cls(UnderstandLogger.from_config(config or UnderstandConfig.from_env()))
17
+
18
+ def emit(self, record: logging.LogRecord) -> None:
19
+ context = {
20
+ "logger_name": record.name,
21
+ "module": record.module,
22
+ "pathname": record.pathname,
23
+ "lineno": record.lineno,
24
+ }
25
+ level = record.levelname.lower()
26
+
27
+ exc_info = record.exc_info
28
+ if exc_info is True:
29
+ exc_info = sys.exc_info()
30
+
31
+ if exc_info and exc_info[1]:
32
+ self.understand_logger.exception(exc_info[1], level=level, context=context)
33
+ return
34
+
35
+ self.understand_logger.log(record.getMessage(), level=level, context=context)
understand/logger.py ADDED
@@ -0,0 +1,162 @@
1
+ import time
2
+ from typing import Any, Dict, Mapping, Optional
3
+
4
+ from .collector import DataCollector
5
+ from .config import UnderstandConfig
6
+ from .encoder import ExceptionEncoder
7
+ from .fields import FieldProvider
8
+ from .handlers import AsyncHandler, BaseHandler, SyncHandler
9
+ from .tokens import TokenProvider
10
+
11
+
12
+ class UnderstandLogger:
13
+ def __init__(
14
+ self,
15
+ config: Optional[UnderstandConfig] = None,
16
+ field_provider: Optional[FieldProvider] = None,
17
+ handler: Optional[BaseHandler] = None,
18
+ encoder: Optional[ExceptionEncoder] = None,
19
+ ) -> None:
20
+ self.config = config or UnderstandConfig()
21
+ self.field_provider = field_provider or FieldProvider(
22
+ config=self.config,
23
+ token_provider=TokenProvider(),
24
+ data_collector=DataCollector(),
25
+ )
26
+ self.handler = handler or self._handler_from_config(self.config)
27
+ if getattr(self.handler, "config", None) is None:
28
+ self.handler.config = self.config
29
+ else:
30
+ self.handler.config = self.config
31
+ self.encoder = encoder or ExceptionEncoder(self.config)
32
+
33
+ @classmethod
34
+ def from_config(
35
+ cls,
36
+ config: Optional[UnderstandConfig] = None,
37
+ handler: Optional[BaseHandler] = None,
38
+ ) -> "UnderstandLogger":
39
+ return cls(config=config or UnderstandConfig.from_env(), handler=handler)
40
+
41
+ def log(
42
+ self,
43
+ message: Any,
44
+ level: str = "error",
45
+ context: Optional[Mapping[str, Any]] = None,
46
+ additional: Optional[Mapping[str, Any]] = None,
47
+ custom_fields: Optional[Mapping[str, Any]] = None,
48
+ ) -> Any:
49
+ if not self._can_deliver(level, message, context):
50
+ return False
51
+
52
+ log = dict(message) if isinstance(message, Mapping) else {"message": message}
53
+ log["message"] = self._format_message(log.get("message"))
54
+ log["level"] = level
55
+ log.setdefault("tags", ["python_log"])
56
+ if context:
57
+ log["context"] = dict(context)
58
+
59
+ event = self._prepare(log, additional or self.event_meta_fields(), custom_fields or {})
60
+ return self._send(event)
61
+
62
+ def error(self, message: Any, level: str = "error", context: Optional[Mapping[str, Any]] = None) -> Any:
63
+ return self.log(message, level=level, context=context)
64
+
65
+ def reset_context(self) -> None:
66
+ self.field_provider.token_provider.generate()
67
+ self.field_provider.data_collector.reset()
68
+
69
+ def exception(
70
+ self,
71
+ exception: BaseException,
72
+ level: str = "error",
73
+ context: Optional[Mapping[str, Any]] = None,
74
+ ) -> Any:
75
+ if not self._can_deliver(level, exception, context):
76
+ return False
77
+
78
+ log = self.encoder.exception_to_dict(exception)
79
+ log["level"] = level
80
+ log["tags"] = ["py_error_log"]
81
+ if context:
82
+ log["context"] = dict(context)
83
+ event = self._prepare(log, self.error_meta_fields(), {})
84
+ return self._send(event)
85
+
86
+ def event_meta_fields(self) -> Dict[str, Any]:
87
+ return {
88
+ "session_id": self.field_provider.get_session_id,
89
+ "request_id": self.field_provider.get_request_id,
90
+ "user_id": self.field_provider.get_user_id,
91
+ "env": self.field_provider.get_environment,
92
+ "url": self.field_provider.get_url,
93
+ "route": self.field_provider.get_route_name,
94
+ "method": self.field_provider.get_request_method,
95
+ "client_ip": self.field_provider.get_client_ip,
96
+ "server_ip": self.field_provider.get_server_ip,
97
+ }
98
+
99
+ def error_meta_fields(self) -> Dict[str, Any]:
100
+ return {
101
+ "session_id": self.field_provider.get_session_id,
102
+ "request_id": self.field_provider.get_request_id,
103
+ "group_id": self.field_provider.get_group_id,
104
+ "user_id": self.field_provider.get_user_id,
105
+ "env": self.field_provider.get_environment,
106
+ "url": self.field_provider.get_url,
107
+ "route": self.field_provider.get_route_name,
108
+ "method": self.field_provider.get_request_method,
109
+ "query_string_data": self.field_provider.get_query_string_array,
110
+ "request_body_data": self.field_provider.get_request_body_data,
111
+ "client_ip": self.field_provider.get_client_ip,
112
+ "server_ip": self.field_provider.get_server_ip,
113
+ "user_agent": self.field_provider.get_client_user_agent,
114
+ "host": self.field_provider.get_host,
115
+ "origin": self.field_provider.get_origin,
116
+ "python_version": self.field_provider.get_python_version,
117
+ "sql_queries": self.field_provider.get_sql_queries,
118
+ "console": self.field_provider.get_console,
119
+ "command": self.field_provider.get_command,
120
+ "logger_version": self.field_provider.get_logger_version,
121
+ }
122
+
123
+ def _prepare(
124
+ self,
125
+ log: Dict[str, Any],
126
+ additional: Mapping[str, Any],
127
+ custom_fields: Mapping[str, Any],
128
+ ) -> Dict[str, Any]:
129
+ data = self.field_provider.resolve_values(additional, log)
130
+ if custom_fields:
131
+ data["custom"] = self.field_provider.resolve_values(custom_fields, log)
132
+ event = dict(data)
133
+ event.update(log)
134
+ event.setdefault("timestamp", round(time.time() * 1000))
135
+ return event
136
+
137
+ def _send(self, event: Dict[str, Any]) -> Any:
138
+ try:
139
+ return self.handler.handle(event)
140
+ except Exception:
141
+ return False
142
+
143
+ def _can_deliver(self, level: str, message: Any, context: Optional[Mapping[str, Any]]) -> bool:
144
+ if not self.config.enabled:
145
+ return False
146
+ if level in self.config.ignored_logs:
147
+ return False
148
+ if self.config.log_filter and self.config.log_filter(level, message, context or {}):
149
+ return False
150
+ return True
151
+
152
+ def _format_message(self, message: Any) -> str:
153
+ if isinstance(message, bool):
154
+ return "1" if message else "0"
155
+ return str(message)
156
+
157
+ def _handler_from_config(self, config: UnderstandConfig) -> BaseHandler:
158
+ if config.handler == "async":
159
+ return AsyncHandler(config)
160
+ if config.handler == "sync":
161
+ return SyncHandler(config)
162
+ raise ValueError("understand handler misconfiguration: " + str(config.handler))
understand/tokens.py ADDED
@@ -0,0 +1,15 @@
1
+ import uuid
2
+
3
+
4
+ class TokenProvider:
5
+ def __init__(self) -> None:
6
+ self._token = ""
7
+ self.generate()
8
+
9
+ def get_token(self) -> str:
10
+ return self._token
11
+
12
+ def generate(self) -> str:
13
+ self._token = str(uuid.uuid4())
14
+ return self._token
15
+
@@ -0,0 +1,202 @@
1
+ Metadata-Version: 2.4
2
+ Name: understand-py
3
+ Version: 0.1.0
4
+ Summary: Framework-neutral Python SDK for sending logs and exceptions to Understand.io.
5
+ Author: Understand
6
+ License-Expression: MIT
7
+ Keywords: understand.io,logging,errors,exceptions
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Dynamic: license-file
22
+
23
+ # Understand Python
24
+
25
+ Framework-neutral Python SDK for sending logs and exceptions to Understand.io.
26
+
27
+ This package is for Python applications. It does not run inside Laravel and it
28
+ does not reimplement the browser JavaScript SDK. Where it shares configuration
29
+ names with the Laravel package, that is config parity only.
30
+
31
+ ## Installation
32
+
33
+ Install from PyPI:
34
+
35
+ ```bash
36
+ python3 -m pip install understand-py
37
+ ```
38
+
39
+ Or add it to `requirements.txt`:
40
+
41
+ ```text
42
+ understand-py
43
+ ```
44
+
45
+ ## Configuration
46
+
47
+ Set your Understand.io input token:
48
+
49
+ ```bash
50
+ export UNDERSTAND_TOKEN="your-input-token"
51
+ export UNDERSTAND_ENV="production"
52
+ ```
53
+
54
+ Or configure it directly in code:
55
+
56
+ ```python
57
+ from understand import UnderstandConfig
58
+
59
+ config = UnderstandConfig(
60
+ token="your-input-token",
61
+ environment="production",
62
+ )
63
+ ```
64
+
65
+ ## Basic Usage
66
+
67
+ Send a log message:
68
+
69
+ ```python
70
+ from understand import UnderstandConfig, UnderstandLogger
71
+
72
+ logger = UnderstandLogger.from_config(
73
+ UnderstandConfig(token="your-input-token", environment="production")
74
+ )
75
+
76
+ logger.error("Understand.io test error", context={"source": "my-app"})
77
+ ```
78
+
79
+ Capture and send an exception:
80
+
81
+ ```python
82
+ from understand import UnderstandConfig, UnderstandLogger
83
+
84
+ logger = UnderstandLogger.from_config(
85
+ UnderstandConfig(token="your-input-token", environment="production")
86
+ )
87
+
88
+ try:
89
+ raise RuntimeError("Payment capture failed")
90
+ except RuntimeError as exc:
91
+ logger.exception(exc, context={"feature": "payments"})
92
+ ```
93
+
94
+ ## Stdlib Logging
95
+
96
+ Attach Understand to Python's built-in `logging` package:
97
+
98
+ ```python
99
+ import logging
100
+
101
+ from understand import UnderstandConfig, UnderstandLogger
102
+ from understand.integrations.logging import UnderstandLoggingHandler
103
+
104
+ understand_logger = UnderstandLogger.from_config(
105
+ UnderstandConfig.from_env()
106
+ )
107
+
108
+ logging.getLogger().addHandler(UnderstandLoggingHandler(understand_logger))
109
+ logging.getLogger().setLevel(logging.INFO)
110
+
111
+ logging.error("This error is sent to Understand.io")
112
+ ```
113
+
114
+ Exceptions logged with `exc_info=True` are sent as structured exception events:
115
+
116
+ ```python
117
+ try:
118
+ raise ValueError("Invalid checkout amount")
119
+ except ValueError:
120
+ logging.exception("Checkout failed")
121
+ ```
122
+
123
+ ## Request Context
124
+
125
+ For web applications, attach request-like metadata before logging:
126
+
127
+ ```python
128
+ from understand import RequestContext, UnderstandConfig, UnderstandLogger
129
+
130
+ logger = UnderstandLogger.from_config(
131
+ UnderstandConfig(token="your-input-token", environment="production")
132
+ )
133
+
134
+ logger.field_provider.set_request_context(
135
+ RequestContext(
136
+ path="/checkout/payments",
137
+ method="POST",
138
+ route_name="payments.create",
139
+ query={"debug": "1"},
140
+ body={"amount": 4999, "password": "hidden automatically"},
141
+ client_ip="203.0.113.10",
142
+ user_agent="Mozilla/5.0",
143
+ user_id="user-123",
144
+ session_id="session-id",
145
+ )
146
+ )
147
+ ```
148
+
149
+ Fields like `password`, `password_confirmation`, `access_token`, `secret_key`,
150
+ `token`, and `access_key` are replaced with `[value hidden]` by default.
151
+
152
+ Environment variables:
153
+
154
+ - `UNDERSTAND_TOKEN`
155
+ - `UNDERSTAND_ENABLED`
156
+ - `UNDERSTAND_API_URL`
157
+ - `UNDERSTAND_HANDLER`
158
+ - `UNDERSTAND_ENV`
159
+ - `UNDERSTAND_SQL`
160
+ - `UNDERSTAND_SQL_BINDINGS`
161
+ - `UNDERSTAND_QUERY_STRING`
162
+ - `UNDERSTAND_REQUEST_BODY`
163
+ - `UNDERSTAND_POST_DATA` as a SDK config-parity alias for request body collection
164
+ - `UNDERSTAND_HIDDEN_REQUEST_FIELDS`
165
+ - `UNDERSTAND_SSL_CA_BUNDLE`
166
+
167
+ For browser JavaScript error tracking, use the separate `understand-js` SDK.
168
+
169
+ ## Long-Running Workers
170
+
171
+ For long-running workers, call `reset_context()` between jobs to regenerate the
172
+ request token and clear collected data:
173
+
174
+ ```python
175
+ for job in jobs:
176
+ logger.reset_context()
177
+
178
+ try:
179
+ process_job(job)
180
+ except Exception as exc:
181
+ logger.exception(exc, context={"job_id": job.id})
182
+ ```
183
+
184
+ ## Local Testing Without Sending Data
185
+
186
+ Use `CallbackHandler` to inspect payloads without making network requests:
187
+
188
+ ```python
189
+ import json
190
+
191
+ from understand import CallbackHandler, UnderstandConfig, UnderstandLogger
192
+
193
+ events = []
194
+ logger = UnderstandLogger.from_config(
195
+ UnderstandConfig(token="test-token", environment="local"),
196
+ handler=CallbackHandler(lambda payload: events.append(json.loads(payload))),
197
+ )
198
+
199
+ logger.error("Local test error")
200
+
201
+ print(json.dumps(events, indent=2))
202
+ ```
@@ -0,0 +1,15 @@
1
+ understand/__init__.py,sha256=Rr0q4VNH2ZOoWOfetBM0PY4LzxH0zLYbJA-S9kkzXwA,606
2
+ understand/collector.py,sha256=w7lJnTvAJ3t2BY9DL-Dg9rC_Atp6WSepbA-ri7753nk,729
3
+ understand/config.py,sha256=cTkGPrDjhmWNiGET4a9K-hTshCwlLbSo3dbZ8gkSAZQ,3047
4
+ understand/encoder.py,sha256=fzNp5Q4bUkEdVTppvhLIkaK8ZGWx4LbotEY1oufyB0k,3623
5
+ understand/fields.py,sha256=oJmPQ1IRaKfRMItULBn6wWnYf5XMm_nWG9XPONdGcJU,8459
6
+ understand/handlers.py,sha256=bH9vD-_F82wYytFha4GrBWf-rzMeau79FaLm9Cwz1uk,2163
7
+ understand/logger.py,sha256=q0a4lZmnm0bNKkgco9xayAYYvZ1gmlg0HjJU8eO-Efg,6411
8
+ understand/tokens.py,sha256=XWCgHaHtSW7kr714P-tI9uvHVtqtlYBzvSRXlBfTWjg,276
9
+ understand/integrations/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
10
+ understand/integrations/logging.py,sha256=u4tuoc-vUuhEiqJUn0A-_zG5a9dOQDOaF_CcAySjpes,1185
11
+ understand_py-0.1.0.dist-info/licenses/LICENSE,sha256=NHJ7d9VWCwf75SOiL_AGi1HTW-YP0Uc61tuv91OFoow,1067
12
+ understand_py-0.1.0.dist-info/METADATA,sha256=1_ir5-AYjmGZl1Khczgr2kuk3dI3ZAzJF0yIy6x_Gu0,5115
13
+ understand_py-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
14
+ understand_py-0.1.0.dist-info/top_level.txt,sha256=8YPA5IZJjDAFG-Xw_Qv2E-1_HJSIzbsXSvD4hughEh4,11
15
+ understand_py-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Understand
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ understand