hyperlog-tools 0.1.1__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.
hyperlog/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ from src.hyperlog.errors import (
2
+ get_log_file,
3
+ log_exception,
4
+ reset_logger,
5
+ )
6
+
7
+ __all__ = [
8
+ "get_log_file",
9
+ "log_exception",
10
+ "reset_logger",
11
+ ]
12
+
13
+ __version__ = "0.1.1"
hyperlog/errors.py ADDED
@@ -0,0 +1,215 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import os
5
+ import re
6
+ import threading
7
+ import traceback
8
+ import uuid
9
+
10
+ from logging.handlers import RotatingFileHandler
11
+ from pathlib import Path
12
+ from types import TracebackType
13
+
14
+ _LOGGER: logging.Logger | None = None
15
+ _LOG_FILE: Path | None = None
16
+ _LOCK = threading.RLock()
17
+
18
+ _LOGGER_NAME = "hyperlog.errors"
19
+ _MAX_LOG_SIZE = 5 * 1024 * 1024
20
+ _BACKUP_COUNT = 5
21
+
22
+
23
+ def _redact(text: str) -> str:
24
+ """Redact common secret values before writing logs."""
25
+ patterns = [
26
+ re.compile(r"""(?ix)
27
+ \b(
28
+ bot[_-]?token |
29
+ api[_-]?key |
30
+ password |
31
+ passwd |
32
+ secret |
33
+ authorization |
34
+ access[_-]?token |
35
+ refresh[_-]?token
36
+ )\b
37
+ (\s*[:=]\s*)
38
+ (["']?)[^\s,;'"&]+
39
+ """),
40
+ re.compile(r"(?i)\bBearer\s+[A-Za-z0-9._~+/=-]+"),
41
+ ]
42
+
43
+ for pattern in patterns:
44
+ if pattern.pattern.startswith("(?i)"):
45
+ text = pattern.sub("Bearer <REDACTED>", text)
46
+ else:
47
+ text = pattern.sub(r"\1\2<REDACTED>", text)
48
+
49
+ return text
50
+
51
+
52
+ def _get_logger() -> logging.Logger:
53
+ """Initialize the logger once, safely across threads."""
54
+ global _LOGGER, _LOG_FILE
55
+
56
+ with _LOCK:
57
+ if _LOGGER is not None:
58
+ return _LOGGER
59
+
60
+ log_dir = Path(
61
+ os.getenv(
62
+ "HYPERLOG_LOG_DIR",
63
+ str(Path.cwd() / "logs"),
64
+ )
65
+ ).expanduser()
66
+
67
+ log_dir.mkdir(parents=True, exist_ok=True)
68
+
69
+ _LOG_FILE = log_dir / "errors.log"
70
+
71
+ logger = logging.getLogger(_LOGGER_NAME)
72
+ logger.setLevel(logging.ERROR)
73
+ logger.propagate = False
74
+
75
+ # Avoid duplicate handlers after repeated initialization.
76
+ for handler in logger.handlers[:]:
77
+ logger.removeHandler(handler)
78
+ handler.close()
79
+
80
+ formatter = logging.Formatter(
81
+ "%(asctime)s | %(levelname)s | %(name)s\n%(message)s",
82
+ datefmt="%Y-%m-%d %H:%M:%S",
83
+ )
84
+
85
+ file_handler = RotatingFileHandler(
86
+ _LOG_FILE,
87
+ maxBytes=_MAX_LOG_SIZE,
88
+ backupCount=_BACKUP_COUNT,
89
+ encoding="utf-8",
90
+ )
91
+ file_handler.setFormatter(formatter)
92
+ logger.addHandler(file_handler)
93
+
94
+ console_handler = logging.StreamHandler()
95
+ console_handler.setFormatter(formatter)
96
+ logger.addHandler(console_handler)
97
+
98
+ _LOGGER = logger
99
+ return logger
100
+
101
+
102
+ def log_exception(
103
+ error: BaseException,
104
+ *,
105
+ context: str | None = None,
106
+ ) -> str:
107
+ """
108
+ Record an exception and return its unique error ID.
109
+
110
+ This function records the error but does not suppress,
111
+ re-raise, or otherwise handle the exception for the caller.
112
+ """
113
+ if not isinstance(error, BaseException):
114
+ raise TypeError("error must be an exception instance")
115
+
116
+ error_id = f"HL-{uuid.uuid4().hex[:12].upper()}"
117
+
118
+ tb: TracebackType | None = error.__traceback__
119
+ frames = traceback.extract_tb(tb) if tb else []
120
+
121
+ if frames:
122
+ # The last frame is the immediate location where the
123
+ # exception was raised.
124
+ frame = frames[-1]
125
+ filename = frame.filename
126
+ function = frame.name
127
+ line = frame.lineno
128
+ else:
129
+ filename = "<unknown>"
130
+ function = "<unknown>"
131
+ line = 0
132
+
133
+ message = str(error) or "<no error message>"
134
+
135
+ if tb is not None:
136
+ full_traceback = "".join(
137
+ traceback.format_exception(
138
+ type(error),
139
+ error,
140
+ tb,
141
+ )
142
+ )
143
+ else:
144
+ full_traceback = "Traceback unavailable: exception has no traceback."
145
+
146
+ details = [
147
+ "=" * 72,
148
+ f"Error ID: {error_id}",
149
+ f"Exception: {type(error).__name__}",
150
+ f"Message: {message}",
151
+ f"File: {filename}",
152
+ f"Function: {function}",
153
+ f"Line: {line}",
154
+ ]
155
+
156
+ if context:
157
+ details.append(f"Context: {context}")
158
+
159
+ details.extend(
160
+ [
161
+ "",
162
+ "Full Traceback:",
163
+ full_traceback.rstrip(),
164
+ "=" * 72,
165
+ ]
166
+ )
167
+
168
+ report = _redact("\n".join(details))
169
+
170
+ # Logging normally should not change the application's
171
+ # exception handling behavior.
172
+ try:
173
+ _get_logger().error("%s", report)
174
+ except OSError:
175
+ # Do not silently claim the log was saved. If logging
176
+ # fails, emit a minimal fallback to stderr.
177
+ import sys
178
+
179
+ print(
180
+ f"HyperLog could not write the log file. " f"Error ID: {error_id}",
181
+ file=sys.stderr,
182
+ )
183
+ print(report, file=sys.stderr)
184
+
185
+ return error_id
186
+
187
+
188
+ def get_log_file() -> Path:
189
+ """Return the configured log file path."""
190
+ _get_logger()
191
+
192
+ if _LOG_FILE is None:
193
+ raise RuntimeError("HyperLog logger was not initialized")
194
+
195
+ return _LOG_FILE
196
+
197
+
198
+ def reset_logger() -> None:
199
+ """
200
+ Close and remove this logger's handlers.
201
+
202
+ Intended for tests or controlled application shutdown.
203
+ The next logging call will initialize it again.
204
+ """
205
+ global _LOGGER, _LOG_FILE
206
+
207
+ with _LOCK:
208
+ logger = logging.getLogger(_LOGGER_NAME)
209
+
210
+ for handler in logger.handlers[:]:
211
+ logger.removeHandler(handler)
212
+ handler.close()
213
+
214
+ _LOGGER = None
215
+ _LOG_FILE = None
hyperlog/functions.py ADDED
@@ -0,0 +1,108 @@
1
+ import asyncio
2
+ import logging
3
+ import re
4
+ import secrets
5
+ import time
6
+
7
+ from collections.abc import Callable
8
+ from typing import TypeVar
9
+
10
+ T = TypeVar("T")
11
+
12
+
13
+ # 1. Generate secure IDs
14
+ def generate_id(length: int = 32) -> str:
15
+ if length < 1:
16
+ raise ValueError("length must be positive")
17
+
18
+ return secrets.token_hex((length + 1) // 2)[:length]
19
+
20
+
21
+ # 2. Clean text
22
+ def clean_text(text: str) -> str:
23
+ if not isinstance(text, str):
24
+ raise TypeError("text must be a string")
25
+
26
+ return re.sub(r"\s+", " ", text).strip()
27
+
28
+
29
+ # 3. Retry synchronous operations
30
+ def retry(
31
+ func: Callable[[], T],
32
+ attempts: int = 3,
33
+ delay: float = 1.0,
34
+ exceptions: tuple = (ConnectionError, TimeoutError),
35
+ ) -> T:
36
+ if attempts < 1:
37
+ raise ValueError("attempts must be at least 1")
38
+
39
+ if delay < 0:
40
+ raise ValueError("delay cannot be negative")
41
+
42
+ for attempt in range(attempts):
43
+ try:
44
+ return func()
45
+ except exceptions:
46
+ if attempt == attempts - 1:
47
+ raise
48
+
49
+ time.sleep(delay)
50
+
51
+ raise RuntimeError("Unexpected retry state")
52
+
53
+
54
+ # 4. Retry asynchronous operations
55
+ async def async_retry(
56
+ func: Callable,
57
+ attempts: int = 3,
58
+ delay: float = 1.0,
59
+ exceptions: tuple = (ConnectionError, TimeoutError),
60
+ ):
61
+ if attempts < 1:
62
+ raise ValueError("attempts must be at least 1")
63
+
64
+ if delay < 0:
65
+ raise ValueError("delay cannot be negative")
66
+
67
+ for attempt in range(attempts):
68
+ try:
69
+ return await func()
70
+ except exceptions:
71
+ if attempt == attempts - 1:
72
+ raise
73
+
74
+ await asyncio.sleep(delay)
75
+
76
+ raise RuntimeError("Unexpected retry state")
77
+
78
+
79
+ # 5. Configure logging
80
+ def setup_logging(
81
+ name: str = "hyperlog",
82
+ file: str = "hyperlog.log",
83
+ level: int = logging.INFO,
84
+ ) -> logging.Logger:
85
+ logger = logging.getLogger(name)
86
+ logger.setLevel(level)
87
+ logger.propagate = False
88
+
89
+ if not logger.handlers:
90
+ formatter = logging.Formatter(
91
+ "%(asctime)s | %(levelname)s | %(name)s | %(message)s",
92
+ datefmt="%Y-%m-%d %H:%M:%S",
93
+ )
94
+
95
+ console = logging.StreamHandler()
96
+ console.setFormatter(formatter)
97
+
98
+ logger.addHandler(console)
99
+
100
+ if file:
101
+ file_handler = logging.FileHandler(
102
+ file,
103
+ encoding="utf-8",
104
+ )
105
+ file_handler.setFormatter(formatter)
106
+ logger.addHandler(file_handler)
107
+
108
+ return logger
@@ -0,0 +1,57 @@
1
+ Metadata-Version: 2.5
2
+ Name: hyperlog-tools
3
+ Version: 0.1.1
4
+ Summary: Reusable Python utilities by Hyper Source
5
+ Author: Hyper Source
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: error-handling,hyperlog,logging,python,utilities
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+
20
+ # Hyperlog
21
+
22
+ Reusable Python utilities developed by Hyper Source.
23
+
24
+ ## Features
25
+
26
+ - Detailed exception logging.
27
+ - Unique error identifiers.
28
+ - Full traceback recording.
29
+ - Automatic log file creation.
30
+ - Log rotation.
31
+ - Common secret redaction.
32
+ - Support for synchronous and asynchronous application errors.
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ pip install hyperlog
38
+ ```
39
+
40
+ ## Quick Start
41
+
42
+ ```python
43
+ from hyperlog import log_exception
44
+
45
+ try:
46
+ int("invalid")
47
+ except ValueError as error:
48
+ error_id = log_exception(
49
+ error,
50
+ context="Input validation",
51
+ )
52
+ print(f"Error ID: {error_id}")
53
+ ```
54
+
55
+ ## License
56
+
57
+ MIT License.
@@ -0,0 +1,7 @@
1
+ hyperlog/__init__.py,sha256=5BjtKocx984nTebEqdllhbm4auzTu43QbIwbThyDWFA,203
2
+ hyperlog/errors.py,sha256=ZhkZQre7F8rmB-5wF_7LH157CrtpWcWDv09W16NFhWs,5641
3
+ hyperlog/functions.py,sha256=0rSJKb8NC5Jss-SKdInqBuczZri2l4sGcIxuu9dLjjs,2618
4
+ hyperlog_tools-0.1.1.dist-info/METADATA,sha256=CvgImbjmkul1umlGcTy3E2-0oZgCArvF2u2XqPW7oSA,1314
5
+ hyperlog_tools-0.1.1.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
6
+ hyperlog_tools-0.1.1.dist-info/licenses/LICENSE,sha256=I3S3F7wdGGX1Hx9XAYuDRQDZ59TTs_O8e70qBXQN4dA,1090
7
+ hyperlog_tools-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hyper Source
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.