loggerbuf 0.9.0__tar.gz

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.
Files changed (45) hide show
  1. loggerbuf-0.9.0/PKG-INFO +340 -0
  2. loggerbuf-0.9.0/README.md +328 -0
  3. loggerbuf-0.9.0/pyproject.toml +27 -0
  4. loggerbuf-0.9.0/setup.cfg +4 -0
  5. loggerbuf-0.9.0/src/loggerbuf/__init__.py +33 -0
  6. loggerbuf-0.9.0/src/loggerbuf/cli/__init__.py +0 -0
  7. loggerbuf-0.9.0/src/loggerbuf/cli/console.py +453 -0
  8. loggerbuf-0.9.0/src/loggerbuf/cli/handlers/__init__.py +0 -0
  9. loggerbuf-0.9.0/src/loggerbuf/cli/handlers/decode.py +234 -0
  10. loggerbuf-0.9.0/src/loggerbuf/cli/handlers/events.py +193 -0
  11. loggerbuf-0.9.0/src/loggerbuf/cli/handlers/fields.py +119 -0
  12. loggerbuf-0.9.0/src/loggerbuf/cli/handlers/protos.py +283 -0
  13. loggerbuf-0.9.0/src/loggerbuf/cli/handlers/stress.py +272 -0
  14. loggerbuf-0.9.0/src/loggerbuf/cli/utils/__init__.py +0 -0
  15. loggerbuf-0.9.0/src/loggerbuf/cli/utils/registry.py +105 -0
  16. loggerbuf-0.9.0/src/loggerbuf/cli/utils/schema_validator.py +138 -0
  17. loggerbuf-0.9.0/src/loggerbuf/config.py +253 -0
  18. loggerbuf-0.9.0/src/loggerbuf/data_logs/__init__.py +5 -0
  19. loggerbuf-0.9.0/src/loggerbuf/data_logs/main_data_pb2.py +39 -0
  20. loggerbuf-0.9.0/src/loggerbuf/data_logs/registry_pb2.py +40 -0
  21. loggerbuf-0.9.0/src/loggerbuf/debugger.py +637 -0
  22. loggerbuf-0.9.0/src/loggerbuf/queue_metrics.py +171 -0
  23. loggerbuf-0.9.0/src/loggerbuf/schema_loader.py +70 -0
  24. loggerbuf-0.9.0/src/loggerbuf/telemetry.py +391 -0
  25. loggerbuf-0.9.0/src/loggerbuf.egg-info/PKG-INFO +340 -0
  26. loggerbuf-0.9.0/src/loggerbuf.egg-info/SOURCES.txt +43 -0
  27. loggerbuf-0.9.0/src/loggerbuf.egg-info/dependency_links.txt +1 -0
  28. loggerbuf-0.9.0/src/loggerbuf.egg-info/entry_points.txt +2 -0
  29. loggerbuf-0.9.0/src/loggerbuf.egg-info/requires.txt +3 -0
  30. loggerbuf-0.9.0/src/loggerbuf.egg-info/top_level.txt +1 -0
  31. loggerbuf-0.9.0/tests/test_cli_decode_debug.py +107 -0
  32. loggerbuf-0.9.0/tests/test_config.py +92 -0
  33. loggerbuf-0.9.0/tests/test_console_cli.py +257 -0
  34. loggerbuf-0.9.0/tests/test_create_classes.py +68 -0
  35. loggerbuf-0.9.0/tests/test_debugger.py +142 -0
  36. loggerbuf-0.9.0/tests/test_debugger_coverage.py +115 -0
  37. loggerbuf-0.9.0/tests/test_decoder.py +103 -0
  38. loggerbuf-0.9.0/tests/test_events_cli.py +105 -0
  39. loggerbuf-0.9.0/tests/test_json_formatter.py +65 -0
  40. loggerbuf-0.9.0/tests/test_protos_coverage.py +58 -0
  41. loggerbuf-0.9.0/tests/test_queue_metrics.py +72 -0
  42. loggerbuf-0.9.0/tests/test_schema_validator.py +75 -0
  43. loggerbuf-0.9.0/tests/test_telemetry.py +98 -0
  44. loggerbuf-0.9.0/tests/test_telemetry_counters.py +68 -0
  45. loggerbuf-0.9.0/tests/test_telemetry_coverage.py +107 -0
@@ -0,0 +1,340 @@
1
+ Metadata-Version: 2.4
2
+ Name: loggerbuf
3
+ Version: 0.9.0
4
+ Summary: A powerful structured telemetry and debugging logger with Protobuf schemas
5
+ Author-email: LoggerBuf Team <hello@loggerbuf.dev>
6
+ Project-URL: Repository, https://github.com/calavraian/LoggerBuf
7
+ Requires-Python: >=3.8
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: protobuf>=5.29.3
10
+ Requires-Dist: click>=8.0.0
11
+ Requires-Dist: psutil
12
+
13
+ # LoggerBuf πŸš€
14
+
15
+ <div align="center">
16
+
17
+ [![PyPI version](https://badge.fury.io/py/loggerbuf.svg)](https://badge.fury.io/py/loggerbuf)
18
+ [![Python Versions](https://img.shields.io/pypi/pyversions/loggerbuf.svg)](https://pypi.org/project/loggerbuf/)
19
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
20
+ [![Build Status](https://github.com/calavraian/LoggerBuf/actions/workflows/python-app.yml/badge.svg)](https://github.com/calavraian/LoggerBuf/actions)
21
+ [![Coverage Status](https://coveralls.io/repos/github/calavraian/LoggerBuf/badge.svg?branch=main)](https://coveralls.io/github/calavraian/LoggerBuf?branch=main)
22
+
23
+ </div>
24
+
25
+ πŸ‡ΊπŸ‡Έ English | πŸ‡ͺπŸ‡Έ [EspaΓ±ol](README.es.md)
26
+
27
+ ### *Structured Telemetry & High-Performance Async Logger for Python*
28
+
29
+ `LoggerBuf` is a high-performance, hybrid logging library designed to solve a classic problem: **the clean separation between operational diagnostic logs (debug) and structured business telemetry events**.
30
+
31
+ Unlike traditional plain-text logging systems that choke under heavy loads and corrupt data, the native implementation of **Protocol Buffers** in `LoggerBuf` guarantees stable, compact, and ultra-fast data schemas. Your information is safely stored in optimized binary files with background automatic rotation and compression, ensuring zero interference with your main application's performance.
32
+
33
+ ---
34
+
35
+ ## πŸš€ Getting Started (Installation & Setup)
36
+
37
+ **1. Installation:**
38
+ Install LoggerBuf in your environment using pip:
39
+ ```bash
40
+ pip install loggerbuf
41
+ ```
42
+
43
+ **2. Initialize the Project:**
44
+ To prep your LoggerBuf project, simply run the master command:
45
+ ```bash
46
+ loggerbuf init
47
+ ```
48
+ This command automatically performs a step-by-step initialization:
49
+ 1. `loggerbuf config init`: Generates `loggerbuf.json` to customize settings.
50
+ 2. `loggerbuf protos init`: Creates the local `loggerbuf_schemas/` directory with the base schemas.
51
+ 3. `loggerbuf build`: Compiles the Python classes automatically.
52
+
53
+ > **[Total Control Note]** If you prefer, instead of using `loggerbuf init`, you can run each of those 3 steps manually one by one. This gives you greater control over each phase of the initialization before the final build.
54
+
55
+ You are now ready to log! You can also run these sub-commands individually if you prefer an iterative setup.
56
+
57
+ ---
58
+
59
+ ## πŸ€” Why LoggerBuf? (The Problem & The Solution)
60
+
61
+ **The Problem:**
62
+ Configuring Python's native `logging` module for production is notoriously complex. If you want asynchronous writing, automatic file rotation, and compression, you end up writing hundreds of lines of boilerplate. Worse, developers often mix operational errors ("Failed to connect to DB") with business analytics ("User completed purchase") in the same giant text files, making data extraction a nightmare.
63
+
64
+ **The Solution:**
65
+ `LoggerBuf` solves this by offering a dual-channel architecture that works out of the box, granting you "free" automatic context for superior tracking and debugging:
66
+ 1. **Debugger**: For operational logs (human-readable text). It automatically injects the exact file, class, and line number into every log without the slow `inspect` magic.
67
+ 2. **Telemetry**: For business analytics. It uses binary Protocol Buffers to ensure your data is always structured, strongly typed, and ready for massive database ingestion.
68
+
69
+ **The "Superpower" (Zero-Setup):**
70
+ With just two lines of code, you get an industrial-grade, non-blocking, auto-rotating logger:
71
+
72
+ ```python
73
+ import loggerbuf
74
+
75
+ # Boom! You now have a fast, async, auto-rotating logger with free context injection.
76
+ log = loggerbuf.create_debugger(name="MAIN_APP")
77
+ log.info("Application started safely.")
78
+ ```
79
+
80
+ ---
81
+
82
+
83
+ ## 🏒 Enterprise Debugging Features
84
+
85
+ LoggerBuf provides advanced, enterprise-grade features that let you fine-tune the debugger output at runtime, without needing to restart your application or change any code.
86
+
87
+ ### 1. Dynamic Console Filtering
88
+ Sometimes you only want to see logs from a specific class or severity level on the console, without stopping the application or affecting the file logs. You can configure this dynamically via `loggerbuf.json`:
89
+ - `LOGGING_CONSOLE_ENABLED`: Turn the console output completely on or off (`true`/`false`).
90
+ - `LOGGING_CONSOLE_ALLOWED_CLASSES`: List of class names to show on the console (e.g., `["PaymentService", "AuthWorker"]`). Leave empty to allow all.
91
+ - `LOGGING_CONSOLE_ALLOWED_LEVELS`: List of log levels to show on the console (e.g., `["ERROR", "CRITICAL"]`). Leave empty to allow all.
92
+
93
+ ### 2. Log Destination & Persistence (History On/Off)
94
+ LoggerBuf gives you complete control over where logs are sent. Persistence is intentional, not forced. You can configure `LOGGING_DESTINATION` via `loggerbuf.json` with 5 different modes:
95
+ - `CONSOLE`: History OFF. Prints beautifully formatted logs to the terminal only. Perfect for local dev.
96
+ - `JSON`: History ON. Writes structured JSON logs to disk. Excellent for log aggregators.
97
+ - `GZIP`: History ON. Writes directly to compressed Gzip files. Ideal for production servers with limited storage.
98
+ - `JSON_AND_CONSOLE`: History ON. Writes to disk and echoes to the terminal.
99
+ - `GZIP_AND_CONSOLE`: History ON. Writes to compressed disk files and echoes to the terminal.
100
+ *(If a misconfiguration occurs, LoggerBuf will safely fallback to `CONSOLE` to ensure you never lose a trace).*
101
+
102
+ ### 3. Configurable Metadata
103
+ By default, the debugger tracks timestamp, logger name, log level, file name, class, function, and line number. You can customize exactly which metadata fields are included in both the JSON file logs and the console output using two distinct keys in your configuration:
104
+ - `LOGGING_METADATA`: Controls what gets saved to disk (JSON/Gzip).
105
+ - `LOGGING_CONSOLE_METADATA`: Controls what is printed on the screen.
106
+
107
+ ```json
108
+ "LOGGING_METADATA": ["TIMESTAMP", "LOGGER", "LEVEL", "MESSAGE"],
109
+ "LOGGING_CONSOLE_METADATA": ["LEVEL", "MESSAGE"]
110
+ ```
111
+ This reduces storage costs and visual noise if you don't need full tracking, and gives you separate controls for what you save versus what you see.
112
+
113
+ ### 4. Complex Object Serialization
114
+ You can pass dictionaries, lists, or custom class instances directly to the logger. LoggerBuf will safely intercept and serialize them to formatted JSON (with a silent fail-safe if an object is unserializable), keeping your code perfectly clean:
115
+ ```python
116
+ user_data = {"id": 123, "role": "admin"}
117
+ log.info(user_data)
118
+ ```
119
+
120
+ ## βš™οΈ Under the Hood (The Technical Engine)
121
+
122
+ * **⚑ Async Background Thread**: Enqueuing a log takes an average of **0.004 ms**. A dedicated background worker handles the heavy lifting of writing to disk, ensuring your main application never blocks.
123
+ * **πŸ“¦ Auto-Rotation & Compression**: Files automatically rotate when they hit a size limit (e.g., 10MB) and historical files are compressed using Gzip in the background to save disk space.
124
+ * **πŸ›‘οΈ Configurable Overflow Profiles**:
125
+ * `LOSSLESS` (Telemetry): Briefly blocks if the queue is full, ensuring not a single analytics event is lost.
126
+ * `LOSSY` (Debugger): Silently discards the oldest logs if the disk is saturated, protecting your app's performance during extreme log bursts.
127
+
128
+ ### πŸ”’ Cryptographic Log Integrity (Tamper-Evident HMAC)
129
+ For highly regulated environments or sensitive telemetry, LoggerBuf supports **Cryptographic Chaining**.
130
+ When enabled via `HMAC_SECRET_KEY` in `loggerbuf.json`, every binary telemetry event is cryptographically signed using `HMAC-SHA256`.
131
+ * **Chained Hashes**: Each event's signature is calculated based on its payload *plus the signature of the previous event*. This forms a cryptographic chain.
132
+ * **File-Level Continuity**: When a file rotates, the last hash is carried over to the new file (`previous_file_hash`). You can verify intermediate files without needing the entire history.
133
+ * **Tamper-Evident**: If an attacker alters a single byte of a past event (or reorders events), the signature of that event and all subsequent events will be invalidated.
134
+ * **Verification**: The `decode-logs` CLI tool automatically verifies signatures if a key is present, instantly halting and emitting a `[!] CRITICAL ALERT` if it detects compromised integrity. (You can bypass this with `--skip-integrity` or provide the key manually via `--verify-key`).
135
+
136
+ ---
137
+
138
+ ## πŸ’» Operational Guide (In the Trenches)
139
+
140
+ ### 1. Operational Diagnostic Logging (Debugger)
141
+ Use the debugger for everyday application monitoring (`debug`, `info`, `warning`, `error`, `critical`).
142
+
143
+ ```python
144
+ class PaymentService:
145
+ def process(self):
146
+ log.info("Processing user payment...")
147
+ try:
148
+ # ... business logic ...
149
+ except Exception as e:
150
+ log.error(f"Transaction failed: {e}")
151
+ ```
152
+ *Notice the "Free Tracking Info" automatically enriched in the output:*
153
+ `[2026-05-29 10:15:30,123] >>MAIN_APP<< (payment.py::PaymentService::process->5) - *INFO* - message::>Processing user payment...`
154
+
155
+ **Understanding the Output Signature:**
156
+ The custom formatter instantly reveals the *where* and *what* of any log entry without requiring you to pass extra context. By default, every log line contains:
157
+ - `[Timestamp]`: Accurate down to milliseconds.
158
+ - `>>LoggerName<<`: Helps isolate which module emitted the log (e.g. `MAIN_APP`, `DB_WORKER`).
159
+ - `(filename.py::ClassName::methodName->lineNumber)`: The exact code location. No more guessing where the error originated.
160
+ - `- *LEVEL* -`: The severity (`INFO`, `ERROR`, etc.).
161
+ - `message::> [Payload]`: The actual log message or serialized JSON object.
162
+
163
+ ### 2. Analytical Event Logging (Telemetry)
164
+ Telemetry uses Protobuf. Every event you track should be categorized using your custom `EventType` and `EventStatus` enums to ensure consistency across your organization. Just like the debugger, Telemetry automatically injects creation timestamps and routing headers behind the scenes.
165
+
166
+ ```python
167
+ from telemetry import TelemetryLog
168
+ from data_logs import Event, EventType, EventStatus
169
+
170
+ # 1. Initialize Logger
171
+ telemetry = TelemetryLog("MAIN")
172
+
173
+ # 2. Create and populate Event
174
+ event = Event()
175
+ event.event_type = EventType.EVENT_DATA_BASE_PROCESSING
176
+ event.general_note = "User successfully registered"
177
+ event.status = EventStatus.STATUS_COMPLETED
178
+
179
+ # Send it to the async binary queue
180
+ telemetry.send(event)
181
+ ```
182
+
183
+ ### 2.1 Simple Metrics (Counters)
184
+ Sometimes a complex event is overkill. If you just want to count occurrences (e.g. "login attempts", "database errors"), you can use the parallel Counters pipeline. This pipeline is **disabled by default** to save resources and avoid starting a second background thread. You must explicitly enable it in `loggerbuf.json` by setting `"METRICS_ENABLED": true`.
185
+
186
+ Counters maintain a segregated pipeline (using their own file under `logs_base_dir/counters`), so they never mix metrics with your main events:
187
+
188
+ ```python
189
+ from telemetry import TelemetryLog
190
+ from data_logs import CounterType
191
+
192
+ telemetry = TelemetryLog("MAIN")
193
+
194
+ # Increment a counter (async, extremely lightweight)
195
+ # If METRICS_ENABLED is false, this call is silently discarded without consuming resources.
196
+ telemetry.increment(CounterType.COUNTER_LOGIN_ATTEMPTS)
197
+
198
+ # You can also increment in batches
199
+ telemetry.increment(CounterType.COUNTER_API_CALLS, value=10)
200
+ ```
201
+ To view your counters, use the CLI tool: `loggerbuf decode-logs <File> --counters`
202
+
203
+ ---
204
+
205
+ ## πŸŽ›οΈ Absolute Control (Advanced Configuration)
206
+
207
+ While the "Zero-Setup" default is great for getting started, advanced developers need absolute control. `LoggerBuf` doesn't lock you in. You can heavily customize rotation sizes, memory queues, and paths globally or per-instance.
208
+
209
+ **1. Global Defaults (`settings_globals.py`)**
210
+ Adjust the engine's core constraints:
211
+ ```python
212
+ LOGGING_FILE_SIZE = 10485760 # Max size per file (10 MB)
213
+ LOGGING_QUEUE_MAX_SIZE = 10000 # Memory queue capacity
214
+ LOGGING_QUEUE_STRATEGY = "lossy" # Overflow behavior
215
+ ```
216
+
217
+ ## βš™οΈ Advanced Settings & Hot Reload
218
+
219
+ LoggerBuf can be globally configured via a `loggerbuf.json` file in your root directory. The easiest way to manage this is via the CLI.
220
+
221
+ ```bash
222
+ loggerbuf config set LOGGING_FILE_SIZE 5000000
223
+ ```
224
+
225
+ > [!TIP]
226
+ > **Zero-Downtime Hot Reload**
227
+ > When you change the `LOG_LEVEL` (e.g. `loggerbuf config set LOG_LEVEL DEBUG`), the underlying active LoggerBuf instances detect the change in the JSON file and will dynamically elevate your log level **without needing to restart the application**. Other structural changes (like file size) will require a manual restart.
228
+
229
+ ### Consolidated Telemetry
230
+ For maximum I/O efficiency, LoggerBuf uses a single JSON file for all debug output (`debug_logs_MAIN.log`). You can easily explore it via:
231
+ ```bash
232
+ loggerbuf decode-debug logs/history/debug_logs_MAIN.log --grep "Error" --tail 50
233
+ ```
234
+
235
+ **2. Instance-Level Overrides**
236
+ You can bypass global settings entirely when creating a logger:
237
+ ```python
238
+ # Create a specialized logger that rotates every 50MB and uses a lossless queue
239
+ custom_log = loggerbuf.create_debugger(
240
+ name="CRITICAL_WORKER",
241
+ max_bytes=52428800,
242
+ queue_strategy="lossless"
243
+ )
244
+ ```
245
+
246
+ ---
247
+
248
+ ## πŸ”§ The CLI (Your Administration Tools)
249
+
250
+ The LoggerBuf CLI (`loggerbuf`) is the **first-class citizen** for managing your telemetry schemas and decoding your binary files.
251
+
252
+ | Command | Description |
253
+ |---|---|
254
+ | `loggerbuf init` | Master command that initializes configuration and schemas at once. |
255
+ | `loggerbuf config init` | Generates the default `loggerbuf.json` configuration file. |
256
+ | `loggerbuf protos init` | Initializes the `loggerbuf_schemas/` directory with base schemas (does not compile). |
257
+ | `loggerbuf build` (or `protos build`) | Runs the Schema Linter and compiles `.proto` to Python, generating an `__init__.py` facade. |
258
+ | `loggerbuf factory-reset` | Safely resets configuration and schemas to their original state (requires security challenge, preserves your historical logs). |
259
+ | `loggerbuf config set <key> <value>` | Safely updates global settings. Example: `loggerbuf config set LOG_LEVEL DEBUG` |
260
+ | `loggerbuf config get <key>` | Retrieves the active value for a key, or prints grouped configurations if you pass `all`, `logging`, `telemetry`, or `metrics`. |
261
+ | `loggerbuf config reset <key>` | Resets a configuration key to its global default value. |
262
+ | `loggerbuf decode-logs <File>` | Decodes binary telemetry logs to Terminal or JSONL. |
263
+ | `loggerbuf event add-type <Name>` | Adds a new sub-classification `EventType` to your project. |
264
+ | `loggerbuf add-counter-type <Type>` | Adds a new counter type to your `registry.proto`. Supports ranges via `--start` and `--end`. |
265
+ | `loggerbuf decode-debug <File>` | Explores historical JSON debug logs visually (supports `--grep`, `--head`, `--tail`). |
266
+
267
+ ### Powerful CLI Examples
268
+
269
+ **1. Decoding Binary Telemetry:**
270
+ Extract thousands of binary events into readable JSON for analysis.
271
+ ```bash
272
+ # Output binary telemetry data as human-readable JSON
273
+ loggerbuf decode-logs logs/telemetry_queue.bin
274
+
275
+ # Decode directly to a JSONL file for database ingestion
276
+ loggerbuf decode-logs logs/telemetry_queue.bin --out output.jsonl
277
+ ```
278
+
279
+ **2. Exploring Debug History:**
280
+ Search through gigabytes of Gzip or JSON operational logs effortlessly using our built-in explorer.
281
+ ```bash
282
+ # Search for 'CRITICAL' in a compressed archive and return the last 20 matches
283
+ loggerbuf decode-debug logs/history/debug_logs.gz --grep "CRITICAL" --tail 20
284
+
285
+ # View the first 50 logs of a standard JSON log file
286
+ loggerbuf decode-debug logs/history/debug_logs.json --head 50
287
+ ```
288
+
289
+ ### Sub-classifying Events (EventType & EventStatus)
290
+ To achieve granular analytics, LoggerBuf allows you to define a hierarchy of sub-classifications (**EventType**) and their respective states (**EventStatus**).
291
+ **Note:** Using custom types and statuses is completely optional. You can always use the default global statuses (e.g. `STATUS_PENDING`, `STATUS_COMPLETED`) for any event if you prefer simplicity.
292
+
293
+ ```bash
294
+ # Add a new EventType for network events, along with two statuses.
295
+ loggerbuf event add-type NETWORK --statuses STARTED,FAILED
296
+
297
+ # Later on, add a new status to the NETWORK type
298
+ loggerbuf event add-status NETWORK TIMEOUT
299
+
300
+ # View your registered types and statuses
301
+ loggerbuf event list
302
+ ```
303
+ *Don't forget to run `loggerbuf build` to compile the changes made by these commands!*
304
+ | `loggerbuf decode-debug <File>` | Explores historical JSON debug logs visually (supports `--grep`, `--head`, `--tail`). |
305
+
306
+ ### πŸ—οΈ Stress Testing & Resource Monitoring
307
+ LoggerBuf includes a built-in concurrent stress testing suite designed to evaluate system performance under extreme logging loads. This command evaluates both disk throughput and queue stability, simulating real-world scenarios.
308
+
309
+ ```bash
310
+ loggerbuf stress-test --threads 10 --writes 50000 --duration 60 --queue-size 10000 --strategy lossy
311
+ ```
312
+
313
+ **Key Parameters:**
314
+ * `--threads`: Number of concurrent threads generating logs.
315
+ * `--writes`: **Total** number of logs to generate across all threads.
316
+ * `--duration`: Spreads the log generation over a target time in seconds. For example, 50,000 writes across 10 threads in 60 seconds will calculate exact millisecond delays (`time.sleep`) per thread to simulate a sustained, realistic traffic load instead of an immediate burst. Use `0` for maximum speed burst testing.
317
+ * `--queue-size` / `--strategy`: Temporarily overrides the internal event queues for the duration of the test.
318
+ * `--keep-logs`: By default, the system runs the test in a temporary isolated `logs/stress_test/` directory and deletes it upon completion to save your disk space. Pass `--keep-logs` to inspect the generated test files. *Note: Running a new test will always clear the previous test's directory.*
319
+
320
+ At the end of the test, LoggerBuf outputs a detailed **Telemetry Queue Metrics Dashboard** along with a **System Resources** summary including Peak CPU, Peak RAM (monitored via `psutil`), and total Disk Space consumed by the test logs.
321
+
322
+ ### πŸ›‘οΈ Schema Evolution (The Golden Rules)
323
+ Because telemetry is stored in binary, **never delete a field or change its data type**.
324
+ `loggerbuf build` includes a **Schema Linter** that compares your files against a historical snapshot and blocks destructive changes.
325
+
326
+ If you need to change a field, use the CLI to deprecate the old one and add a new one safely:
327
+ ```bash
328
+ loggerbuf deprecate-subfield DemoUserEvent "new_metric"
329
+ loggerbuf add-subfield DemoUserEvent "new_metric_str" "string"
330
+ loggerbuf build
331
+ ```
332
+
333
+ ---
334
+
335
+ ## 🧠 The "Giant Proto" Myth
336
+
337
+ `main_data.proto` acts as a giant wrapper containing *every single event* your system can emit.
338
+
339
+ **Does this mean every log entry is massive? No.**
340
+ Protobuf is extremely efficient. Unpopulated fields take up **zero bytes** on disk. Even if your schema has 500 different events, a serialized log entry will only consume the exact bytes of the 1 event you actually populated.
@@ -0,0 +1,328 @@
1
+ # LoggerBuf πŸš€
2
+
3
+ <div align="center">
4
+
5
+ [![PyPI version](https://badge.fury.io/py/loggerbuf.svg)](https://badge.fury.io/py/loggerbuf)
6
+ [![Python Versions](https://img.shields.io/pypi/pyversions/loggerbuf.svg)](https://pypi.org/project/loggerbuf/)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
+ [![Build Status](https://github.com/calavraian/LoggerBuf/actions/workflows/python-app.yml/badge.svg)](https://github.com/calavraian/LoggerBuf/actions)
9
+ [![Coverage Status](https://coveralls.io/repos/github/calavraian/LoggerBuf/badge.svg?branch=main)](https://coveralls.io/github/calavraian/LoggerBuf?branch=main)
10
+
11
+ </div>
12
+
13
+ πŸ‡ΊπŸ‡Έ English | πŸ‡ͺπŸ‡Έ [EspaΓ±ol](README.es.md)
14
+
15
+ ### *Structured Telemetry & High-Performance Async Logger for Python*
16
+
17
+ `LoggerBuf` is a high-performance, hybrid logging library designed to solve a classic problem: **the clean separation between operational diagnostic logs (debug) and structured business telemetry events**.
18
+
19
+ Unlike traditional plain-text logging systems that choke under heavy loads and corrupt data, the native implementation of **Protocol Buffers** in `LoggerBuf` guarantees stable, compact, and ultra-fast data schemas. Your information is safely stored in optimized binary files with background automatic rotation and compression, ensuring zero interference with your main application's performance.
20
+
21
+ ---
22
+
23
+ ## πŸš€ Getting Started (Installation & Setup)
24
+
25
+ **1. Installation:**
26
+ Install LoggerBuf in your environment using pip:
27
+ ```bash
28
+ pip install loggerbuf
29
+ ```
30
+
31
+ **2. Initialize the Project:**
32
+ To prep your LoggerBuf project, simply run the master command:
33
+ ```bash
34
+ loggerbuf init
35
+ ```
36
+ This command automatically performs a step-by-step initialization:
37
+ 1. `loggerbuf config init`: Generates `loggerbuf.json` to customize settings.
38
+ 2. `loggerbuf protos init`: Creates the local `loggerbuf_schemas/` directory with the base schemas.
39
+ 3. `loggerbuf build`: Compiles the Python classes automatically.
40
+
41
+ > **[Total Control Note]** If you prefer, instead of using `loggerbuf init`, you can run each of those 3 steps manually one by one. This gives you greater control over each phase of the initialization before the final build.
42
+
43
+ You are now ready to log! You can also run these sub-commands individually if you prefer an iterative setup.
44
+
45
+ ---
46
+
47
+ ## πŸ€” Why LoggerBuf? (The Problem & The Solution)
48
+
49
+ **The Problem:**
50
+ Configuring Python's native `logging` module for production is notoriously complex. If you want asynchronous writing, automatic file rotation, and compression, you end up writing hundreds of lines of boilerplate. Worse, developers often mix operational errors ("Failed to connect to DB") with business analytics ("User completed purchase") in the same giant text files, making data extraction a nightmare.
51
+
52
+ **The Solution:**
53
+ `LoggerBuf` solves this by offering a dual-channel architecture that works out of the box, granting you "free" automatic context for superior tracking and debugging:
54
+ 1. **Debugger**: For operational logs (human-readable text). It automatically injects the exact file, class, and line number into every log without the slow `inspect` magic.
55
+ 2. **Telemetry**: For business analytics. It uses binary Protocol Buffers to ensure your data is always structured, strongly typed, and ready for massive database ingestion.
56
+
57
+ **The "Superpower" (Zero-Setup):**
58
+ With just two lines of code, you get an industrial-grade, non-blocking, auto-rotating logger:
59
+
60
+ ```python
61
+ import loggerbuf
62
+
63
+ # Boom! You now have a fast, async, auto-rotating logger with free context injection.
64
+ log = loggerbuf.create_debugger(name="MAIN_APP")
65
+ log.info("Application started safely.")
66
+ ```
67
+
68
+ ---
69
+
70
+
71
+ ## 🏒 Enterprise Debugging Features
72
+
73
+ LoggerBuf provides advanced, enterprise-grade features that let you fine-tune the debugger output at runtime, without needing to restart your application or change any code.
74
+
75
+ ### 1. Dynamic Console Filtering
76
+ Sometimes you only want to see logs from a specific class or severity level on the console, without stopping the application or affecting the file logs. You can configure this dynamically via `loggerbuf.json`:
77
+ - `LOGGING_CONSOLE_ENABLED`: Turn the console output completely on or off (`true`/`false`).
78
+ - `LOGGING_CONSOLE_ALLOWED_CLASSES`: List of class names to show on the console (e.g., `["PaymentService", "AuthWorker"]`). Leave empty to allow all.
79
+ - `LOGGING_CONSOLE_ALLOWED_LEVELS`: List of log levels to show on the console (e.g., `["ERROR", "CRITICAL"]`). Leave empty to allow all.
80
+
81
+ ### 2. Log Destination & Persistence (History On/Off)
82
+ LoggerBuf gives you complete control over where logs are sent. Persistence is intentional, not forced. You can configure `LOGGING_DESTINATION` via `loggerbuf.json` with 5 different modes:
83
+ - `CONSOLE`: History OFF. Prints beautifully formatted logs to the terminal only. Perfect for local dev.
84
+ - `JSON`: History ON. Writes structured JSON logs to disk. Excellent for log aggregators.
85
+ - `GZIP`: History ON. Writes directly to compressed Gzip files. Ideal for production servers with limited storage.
86
+ - `JSON_AND_CONSOLE`: History ON. Writes to disk and echoes to the terminal.
87
+ - `GZIP_AND_CONSOLE`: History ON. Writes to compressed disk files and echoes to the terminal.
88
+ *(If a misconfiguration occurs, LoggerBuf will safely fallback to `CONSOLE` to ensure you never lose a trace).*
89
+
90
+ ### 3. Configurable Metadata
91
+ By default, the debugger tracks timestamp, logger name, log level, file name, class, function, and line number. You can customize exactly which metadata fields are included in both the JSON file logs and the console output using two distinct keys in your configuration:
92
+ - `LOGGING_METADATA`: Controls what gets saved to disk (JSON/Gzip).
93
+ - `LOGGING_CONSOLE_METADATA`: Controls what is printed on the screen.
94
+
95
+ ```json
96
+ "LOGGING_METADATA": ["TIMESTAMP", "LOGGER", "LEVEL", "MESSAGE"],
97
+ "LOGGING_CONSOLE_METADATA": ["LEVEL", "MESSAGE"]
98
+ ```
99
+ This reduces storage costs and visual noise if you don't need full tracking, and gives you separate controls for what you save versus what you see.
100
+
101
+ ### 4. Complex Object Serialization
102
+ You can pass dictionaries, lists, or custom class instances directly to the logger. LoggerBuf will safely intercept and serialize them to formatted JSON (with a silent fail-safe if an object is unserializable), keeping your code perfectly clean:
103
+ ```python
104
+ user_data = {"id": 123, "role": "admin"}
105
+ log.info(user_data)
106
+ ```
107
+
108
+ ## βš™οΈ Under the Hood (The Technical Engine)
109
+
110
+ * **⚑ Async Background Thread**: Enqueuing a log takes an average of **0.004 ms**. A dedicated background worker handles the heavy lifting of writing to disk, ensuring your main application never blocks.
111
+ * **πŸ“¦ Auto-Rotation & Compression**: Files automatically rotate when they hit a size limit (e.g., 10MB) and historical files are compressed using Gzip in the background to save disk space.
112
+ * **πŸ›‘οΈ Configurable Overflow Profiles**:
113
+ * `LOSSLESS` (Telemetry): Briefly blocks if the queue is full, ensuring not a single analytics event is lost.
114
+ * `LOSSY` (Debugger): Silently discards the oldest logs if the disk is saturated, protecting your app's performance during extreme log bursts.
115
+
116
+ ### πŸ”’ Cryptographic Log Integrity (Tamper-Evident HMAC)
117
+ For highly regulated environments or sensitive telemetry, LoggerBuf supports **Cryptographic Chaining**.
118
+ When enabled via `HMAC_SECRET_KEY` in `loggerbuf.json`, every binary telemetry event is cryptographically signed using `HMAC-SHA256`.
119
+ * **Chained Hashes**: Each event's signature is calculated based on its payload *plus the signature of the previous event*. This forms a cryptographic chain.
120
+ * **File-Level Continuity**: When a file rotates, the last hash is carried over to the new file (`previous_file_hash`). You can verify intermediate files without needing the entire history.
121
+ * **Tamper-Evident**: If an attacker alters a single byte of a past event (or reorders events), the signature of that event and all subsequent events will be invalidated.
122
+ * **Verification**: The `decode-logs` CLI tool automatically verifies signatures if a key is present, instantly halting and emitting a `[!] CRITICAL ALERT` if it detects compromised integrity. (You can bypass this with `--skip-integrity` or provide the key manually via `--verify-key`).
123
+
124
+ ---
125
+
126
+ ## πŸ’» Operational Guide (In the Trenches)
127
+
128
+ ### 1. Operational Diagnostic Logging (Debugger)
129
+ Use the debugger for everyday application monitoring (`debug`, `info`, `warning`, `error`, `critical`).
130
+
131
+ ```python
132
+ class PaymentService:
133
+ def process(self):
134
+ log.info("Processing user payment...")
135
+ try:
136
+ # ... business logic ...
137
+ except Exception as e:
138
+ log.error(f"Transaction failed: {e}")
139
+ ```
140
+ *Notice the "Free Tracking Info" automatically enriched in the output:*
141
+ `[2026-05-29 10:15:30,123] >>MAIN_APP<< (payment.py::PaymentService::process->5) - *INFO* - message::>Processing user payment...`
142
+
143
+ **Understanding the Output Signature:**
144
+ The custom formatter instantly reveals the *where* and *what* of any log entry without requiring you to pass extra context. By default, every log line contains:
145
+ - `[Timestamp]`: Accurate down to milliseconds.
146
+ - `>>LoggerName<<`: Helps isolate which module emitted the log (e.g. `MAIN_APP`, `DB_WORKER`).
147
+ - `(filename.py::ClassName::methodName->lineNumber)`: The exact code location. No more guessing where the error originated.
148
+ - `- *LEVEL* -`: The severity (`INFO`, `ERROR`, etc.).
149
+ - `message::> [Payload]`: The actual log message or serialized JSON object.
150
+
151
+ ### 2. Analytical Event Logging (Telemetry)
152
+ Telemetry uses Protobuf. Every event you track should be categorized using your custom `EventType` and `EventStatus` enums to ensure consistency across your organization. Just like the debugger, Telemetry automatically injects creation timestamps and routing headers behind the scenes.
153
+
154
+ ```python
155
+ from telemetry import TelemetryLog
156
+ from data_logs import Event, EventType, EventStatus
157
+
158
+ # 1. Initialize Logger
159
+ telemetry = TelemetryLog("MAIN")
160
+
161
+ # 2. Create and populate Event
162
+ event = Event()
163
+ event.event_type = EventType.EVENT_DATA_BASE_PROCESSING
164
+ event.general_note = "User successfully registered"
165
+ event.status = EventStatus.STATUS_COMPLETED
166
+
167
+ # Send it to the async binary queue
168
+ telemetry.send(event)
169
+ ```
170
+
171
+ ### 2.1 Simple Metrics (Counters)
172
+ Sometimes a complex event is overkill. If you just want to count occurrences (e.g. "login attempts", "database errors"), you can use the parallel Counters pipeline. This pipeline is **disabled by default** to save resources and avoid starting a second background thread. You must explicitly enable it in `loggerbuf.json` by setting `"METRICS_ENABLED": true`.
173
+
174
+ Counters maintain a segregated pipeline (using their own file under `logs_base_dir/counters`), so they never mix metrics with your main events:
175
+
176
+ ```python
177
+ from telemetry import TelemetryLog
178
+ from data_logs import CounterType
179
+
180
+ telemetry = TelemetryLog("MAIN")
181
+
182
+ # Increment a counter (async, extremely lightweight)
183
+ # If METRICS_ENABLED is false, this call is silently discarded without consuming resources.
184
+ telemetry.increment(CounterType.COUNTER_LOGIN_ATTEMPTS)
185
+
186
+ # You can also increment in batches
187
+ telemetry.increment(CounterType.COUNTER_API_CALLS, value=10)
188
+ ```
189
+ To view your counters, use the CLI tool: `loggerbuf decode-logs <File> --counters`
190
+
191
+ ---
192
+
193
+ ## πŸŽ›οΈ Absolute Control (Advanced Configuration)
194
+
195
+ While the "Zero-Setup" default is great for getting started, advanced developers need absolute control. `LoggerBuf` doesn't lock you in. You can heavily customize rotation sizes, memory queues, and paths globally or per-instance.
196
+
197
+ **1. Global Defaults (`settings_globals.py`)**
198
+ Adjust the engine's core constraints:
199
+ ```python
200
+ LOGGING_FILE_SIZE = 10485760 # Max size per file (10 MB)
201
+ LOGGING_QUEUE_MAX_SIZE = 10000 # Memory queue capacity
202
+ LOGGING_QUEUE_STRATEGY = "lossy" # Overflow behavior
203
+ ```
204
+
205
+ ## βš™οΈ Advanced Settings & Hot Reload
206
+
207
+ LoggerBuf can be globally configured via a `loggerbuf.json` file in your root directory. The easiest way to manage this is via the CLI.
208
+
209
+ ```bash
210
+ loggerbuf config set LOGGING_FILE_SIZE 5000000
211
+ ```
212
+
213
+ > [!TIP]
214
+ > **Zero-Downtime Hot Reload**
215
+ > When you change the `LOG_LEVEL` (e.g. `loggerbuf config set LOG_LEVEL DEBUG`), the underlying active LoggerBuf instances detect the change in the JSON file and will dynamically elevate your log level **without needing to restart the application**. Other structural changes (like file size) will require a manual restart.
216
+
217
+ ### Consolidated Telemetry
218
+ For maximum I/O efficiency, LoggerBuf uses a single JSON file for all debug output (`debug_logs_MAIN.log`). You can easily explore it via:
219
+ ```bash
220
+ loggerbuf decode-debug logs/history/debug_logs_MAIN.log --grep "Error" --tail 50
221
+ ```
222
+
223
+ **2. Instance-Level Overrides**
224
+ You can bypass global settings entirely when creating a logger:
225
+ ```python
226
+ # Create a specialized logger that rotates every 50MB and uses a lossless queue
227
+ custom_log = loggerbuf.create_debugger(
228
+ name="CRITICAL_WORKER",
229
+ max_bytes=52428800,
230
+ queue_strategy="lossless"
231
+ )
232
+ ```
233
+
234
+ ---
235
+
236
+ ## πŸ”§ The CLI (Your Administration Tools)
237
+
238
+ The LoggerBuf CLI (`loggerbuf`) is the **first-class citizen** for managing your telemetry schemas and decoding your binary files.
239
+
240
+ | Command | Description |
241
+ |---|---|
242
+ | `loggerbuf init` | Master command that initializes configuration and schemas at once. |
243
+ | `loggerbuf config init` | Generates the default `loggerbuf.json` configuration file. |
244
+ | `loggerbuf protos init` | Initializes the `loggerbuf_schemas/` directory with base schemas (does not compile). |
245
+ | `loggerbuf build` (or `protos build`) | Runs the Schema Linter and compiles `.proto` to Python, generating an `__init__.py` facade. |
246
+ | `loggerbuf factory-reset` | Safely resets configuration and schemas to their original state (requires security challenge, preserves your historical logs). |
247
+ | `loggerbuf config set <key> <value>` | Safely updates global settings. Example: `loggerbuf config set LOG_LEVEL DEBUG` |
248
+ | `loggerbuf config get <key>` | Retrieves the active value for a key, or prints grouped configurations if you pass `all`, `logging`, `telemetry`, or `metrics`. |
249
+ | `loggerbuf config reset <key>` | Resets a configuration key to its global default value. |
250
+ | `loggerbuf decode-logs <File>` | Decodes binary telemetry logs to Terminal or JSONL. |
251
+ | `loggerbuf event add-type <Name>` | Adds a new sub-classification `EventType` to your project. |
252
+ | `loggerbuf add-counter-type <Type>` | Adds a new counter type to your `registry.proto`. Supports ranges via `--start` and `--end`. |
253
+ | `loggerbuf decode-debug <File>` | Explores historical JSON debug logs visually (supports `--grep`, `--head`, `--tail`). |
254
+
255
+ ### Powerful CLI Examples
256
+
257
+ **1. Decoding Binary Telemetry:**
258
+ Extract thousands of binary events into readable JSON for analysis.
259
+ ```bash
260
+ # Output binary telemetry data as human-readable JSON
261
+ loggerbuf decode-logs logs/telemetry_queue.bin
262
+
263
+ # Decode directly to a JSONL file for database ingestion
264
+ loggerbuf decode-logs logs/telemetry_queue.bin --out output.jsonl
265
+ ```
266
+
267
+ **2. Exploring Debug History:**
268
+ Search through gigabytes of Gzip or JSON operational logs effortlessly using our built-in explorer.
269
+ ```bash
270
+ # Search for 'CRITICAL' in a compressed archive and return the last 20 matches
271
+ loggerbuf decode-debug logs/history/debug_logs.gz --grep "CRITICAL" --tail 20
272
+
273
+ # View the first 50 logs of a standard JSON log file
274
+ loggerbuf decode-debug logs/history/debug_logs.json --head 50
275
+ ```
276
+
277
+ ### Sub-classifying Events (EventType & EventStatus)
278
+ To achieve granular analytics, LoggerBuf allows you to define a hierarchy of sub-classifications (**EventType**) and their respective states (**EventStatus**).
279
+ **Note:** Using custom types and statuses is completely optional. You can always use the default global statuses (e.g. `STATUS_PENDING`, `STATUS_COMPLETED`) for any event if you prefer simplicity.
280
+
281
+ ```bash
282
+ # Add a new EventType for network events, along with two statuses.
283
+ loggerbuf event add-type NETWORK --statuses STARTED,FAILED
284
+
285
+ # Later on, add a new status to the NETWORK type
286
+ loggerbuf event add-status NETWORK TIMEOUT
287
+
288
+ # View your registered types and statuses
289
+ loggerbuf event list
290
+ ```
291
+ *Don't forget to run `loggerbuf build` to compile the changes made by these commands!*
292
+ | `loggerbuf decode-debug <File>` | Explores historical JSON debug logs visually (supports `--grep`, `--head`, `--tail`). |
293
+
294
+ ### πŸ—οΈ Stress Testing & Resource Monitoring
295
+ LoggerBuf includes a built-in concurrent stress testing suite designed to evaluate system performance under extreme logging loads. This command evaluates both disk throughput and queue stability, simulating real-world scenarios.
296
+
297
+ ```bash
298
+ loggerbuf stress-test --threads 10 --writes 50000 --duration 60 --queue-size 10000 --strategy lossy
299
+ ```
300
+
301
+ **Key Parameters:**
302
+ * `--threads`: Number of concurrent threads generating logs.
303
+ * `--writes`: **Total** number of logs to generate across all threads.
304
+ * `--duration`: Spreads the log generation over a target time in seconds. For example, 50,000 writes across 10 threads in 60 seconds will calculate exact millisecond delays (`time.sleep`) per thread to simulate a sustained, realistic traffic load instead of an immediate burst. Use `0` for maximum speed burst testing.
305
+ * `--queue-size` / `--strategy`: Temporarily overrides the internal event queues for the duration of the test.
306
+ * `--keep-logs`: By default, the system runs the test in a temporary isolated `logs/stress_test/` directory and deletes it upon completion to save your disk space. Pass `--keep-logs` to inspect the generated test files. *Note: Running a new test will always clear the previous test's directory.*
307
+
308
+ At the end of the test, LoggerBuf outputs a detailed **Telemetry Queue Metrics Dashboard** along with a **System Resources** summary including Peak CPU, Peak RAM (monitored via `psutil`), and total Disk Space consumed by the test logs.
309
+
310
+ ### πŸ›‘οΈ Schema Evolution (The Golden Rules)
311
+ Because telemetry is stored in binary, **never delete a field or change its data type**.
312
+ `loggerbuf build` includes a **Schema Linter** that compares your files against a historical snapshot and blocks destructive changes.
313
+
314
+ If you need to change a field, use the CLI to deprecate the old one and add a new one safely:
315
+ ```bash
316
+ loggerbuf deprecate-subfield DemoUserEvent "new_metric"
317
+ loggerbuf add-subfield DemoUserEvent "new_metric_str" "string"
318
+ loggerbuf build
319
+ ```
320
+
321
+ ---
322
+
323
+ ## 🧠 The "Giant Proto" Myth
324
+
325
+ `main_data.proto` acts as a giant wrapper containing *every single event* your system can emit.
326
+
327
+ **Does this mean every log entry is massive? No.**
328
+ Protobuf is extremely efficient. Unpopulated fields take up **zero bytes** on disk. Even if your schema has 500 different events, a serialized log entry will only consume the exact bytes of the 1 event you actually populated.