logreducer 3.5.5__tar.gz → 3.5.7__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.
- {logreducer-3.5.5 → logreducer-3.5.7}/PKG-INFO +12 -13
- {logreducer-3.5.5 → logreducer-3.5.7}/docs/pypi.md +10 -11
- {logreducer-3.5.5 → logreducer-3.5.7}/pyproject.toml +14 -14
- {logreducer-3.5.5 → logreducer-3.5.7}/pyproject.toml.orig +14 -14
- logreducer-3.5.7/src/logreducer/anomaly.py +95 -0
- {logreducer-3.5.5 → logreducer-3.5.7}/src/logreducer/cli.py +15 -4
- {logreducer-3.5.5 → logreducer-3.5.7}/src/logreducer/config.py +9 -6
- {logreducer-3.5.5 → logreducer-3.5.7}/src/logreducer/core.py +64 -42
- {logreducer-3.5.5 → logreducer-3.5.7}/src/logreducer/kafka.py +143 -67
- {logreducer-3.5.5 → logreducer-3.5.7}/src/logreducer/logging_config.py +3 -2
- {logreducer-3.5.5 → logreducer-3.5.7}/src/logreducer/memory.py +1 -1
- {logreducer-3.5.5 → logreducer-3.5.7}/src/logreducer/patterns.py +158 -27
- {logreducer-3.5.5 → logreducer-3.5.7}/src/logreducer/sampling.py +59 -28
- {logreducer-3.5.5 → logreducer-3.5.7}/src/logreducer/sources.py +8 -3
- {logreducer-3.5.5 → logreducer-3.5.7}/src/logreducer/sql.py +31 -6
- {logreducer-3.5.5 → logreducer-3.5.7}/src/logreducer/target.py +5 -4
- {logreducer-3.5.5 → logreducer-3.5.7}/src/logreducer/template_mining.py +62 -9
- {logreducer-3.5.5 → logreducer-3.5.7}/src/logreducer/temporal.py +41 -19
- logreducer-3.5.5/src/logreducer/anomaly.py +0 -74
- {logreducer-3.5.5 → logreducer-3.5.7}/LICENSE +0 -0
- {logreducer-3.5.5 → logreducer-3.5.7}/NOTICE +0 -0
- {logreducer-3.5.5 → logreducer-3.5.7}/src/logreducer/__init__.py +0 -0
- {logreducer-3.5.5 → logreducer-3.5.7}/src/logreducer/clickhouse.py +0 -0
- {logreducer-3.5.5 → logreducer-3.5.7}/src/logreducer/py.typed +0 -0
- {logreducer-3.5.5 → logreducer-3.5.7}/src/logreducer/sinks.py +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: logreducer
|
|
3
|
-
Version: 3.5.
|
|
4
|
-
Summary:
|
|
3
|
+
Version: 3.5.7
|
|
4
|
+
Summary: Reduces gigabytes of logs to a small, representative sample, as a CLI or a Python library.
|
|
5
5
|
Keywords: log,logging,reduction,analysis,pattern-extraction,memory-efficient,streaming,anomaly-detection
|
|
6
6
|
Author: HyperI Team
|
|
7
7
|
Author-email: HyperI Team <dev@hyperi.io>
|
|
@@ -49,16 +49,15 @@ It ships as a CLI and as a Python library with an IO-agnostic core.
|
|
|
49
49
|
## What it gives you
|
|
50
50
|
|
|
51
51
|
- A `logreducer` command that reduces a file, a SQL or ClickHouse query, or a Kafka topic, straight from the shell.
|
|
52
|
-
- Pattern mode streams through a bounded dedup cache and template store, so memory
|
|
52
|
+
- Pattern mode streams through a bounded dedup cache, fuzzy index and template store, so memory does not grow with the line count. Line length and the spread of token counts per line still add to it.
|
|
53
53
|
- A memory budget that decides how a file is read: whole, in chunks, or reservoir-sampled once it passes five times the budget.
|
|
54
54
|
- Four modes: pattern (Drain3 template mining), anomaly (Isolation Forest), temporal (one example per template per time window) and hybrid.
|
|
55
|
-
- ERROR, FATAL
|
|
55
|
+
- Lines naming ERROR, FATAL or CRITICAL as a whole word, in any case, come through ahead of the reduced output, one per distinct message once standalone numbers, IPs, MACs, UUIDs, hex IDs and ISO timestamps are masked, in every mode and however a file is read, up to `max_severe_shapes` messages (`max_patterns` by default). A SQL or ClickHouse source samples in the database first, so a line the sample drops is never seen.
|
|
56
56
|
- A core with no IO dependencies: anything re-iterable that yields `str` lines is a source, and anything with `write(lines)` is a sink.
|
|
57
|
-
- Seeded SQL sampling and ClickHouse `SAMPLE` for tables
|
|
58
|
-
-
|
|
59
|
-
- Injection points for a host application's own config cascade and logging.
|
|
57
|
+
- Seeded SQL sampling, PostgreSQL `TABLESAMPLE` and ClickHouse `SAMPLE` for large tables, and `reduce_to_target` to collect about N representative lines from a large source, holding roughly one batch in memory.
|
|
58
|
+
- Injection points for a host application's config cascade and logging.
|
|
60
59
|
|
|
61
|
-
|
|
60
|
+
Install it and reduce a list of lines:
|
|
62
61
|
|
|
63
62
|
```console
|
|
64
63
|
uv add logreducer
|
|
@@ -76,7 +75,7 @@ for line in reduced:
|
|
|
76
75
|
print(line)
|
|
77
76
|
```
|
|
78
77
|
|
|
79
|
-
```
|
|
78
|
+
```console
|
|
80
79
|
540 -> 4
|
|
81
80
|
WARN slow query table=events ms=300
|
|
82
81
|
WARN slow query table=events ms=301
|
|
@@ -86,15 +85,15 @@ INFO GET /health 200 req=1
|
|
|
86
85
|
|
|
87
86
|
From the shell it is `logreducer app.log -o reduced.log`. `level` is `standard`, `enhanced` or `maximum`, trading speed for wider coverage on a 0.5, 1 or 2 GB budget.
|
|
88
87
|
|
|
89
|
-
|
|
88
|
+
Extras add adapters and fuzzy dedup:
|
|
90
89
|
|
|
91
90
|
| Extra | Adds |
|
|
92
91
|
|---|---|
|
|
93
|
-
| `enhanced` | Fuzzy dedup with MinHash LSH
|
|
94
|
-
| `sql` | `SQLSource` over SQLAlchemy, with
|
|
92
|
+
| `enhanced` | Fuzzy dedup with MinHash LSH (the index holds the last `dedup_cache_size` near-unique lines) and faster hashing |
|
|
93
|
+
| `sql` | `SQLSource` over SQLAlchemy, with a DBAPI driver you install |
|
|
95
94
|
| `clickhouse` | `ClickHouseSource` over clickhouse-connect |
|
|
96
95
|
| `kafka` | `KafkaSource` and `KafkaSink` over confluent-kafka |
|
|
97
96
|
|
|
98
97
|
Template mining is derived from [Drain3](https://github.com/logpai/Drain3), MIT licence, with its licence text in the module header.
|
|
99
98
|
|
|
100
|
-
Docs and source are at <https://github.com/hyperi-io/logreducer>.
|
|
99
|
+
Docs and source are at <https://github.com/hyperi-io/logreducer>. PyPI lists the Python floor under Meta. Licensed Apache-2.0: <https://github.com/hyperi-io/logreducer/blob/main/LICENSE>.
|
|
@@ -7,16 +7,15 @@ It ships as a CLI and as a Python library with an IO-agnostic core.
|
|
|
7
7
|
## What it gives you
|
|
8
8
|
|
|
9
9
|
- A `logreducer` command that reduces a file, a SQL or ClickHouse query, or a Kafka topic, straight from the shell.
|
|
10
|
-
- Pattern mode streams through a bounded dedup cache and template store, so memory
|
|
10
|
+
- Pattern mode streams through a bounded dedup cache, fuzzy index and template store, so memory does not grow with the line count. Line length and the spread of token counts per line still add to it.
|
|
11
11
|
- A memory budget that decides how a file is read: whole, in chunks, or reservoir-sampled once it passes five times the budget.
|
|
12
12
|
- Four modes: pattern (Drain3 template mining), anomaly (Isolation Forest), temporal (one example per template per time window) and hybrid.
|
|
13
|
-
- ERROR, FATAL
|
|
13
|
+
- Lines naming ERROR, FATAL or CRITICAL as a whole word, in any case, come through ahead of the reduced output, one per distinct message once standalone numbers, IPs, MACs, UUIDs, hex IDs and ISO timestamps are masked, in every mode and however a file is read, up to `max_severe_shapes` messages (`max_patterns` by default). A SQL or ClickHouse source samples in the database first, so a line the sample drops is never seen.
|
|
14
14
|
- A core with no IO dependencies: anything re-iterable that yields `str` lines is a source, and anything with `write(lines)` is a sink.
|
|
15
|
-
- Seeded SQL sampling and ClickHouse `SAMPLE` for tables
|
|
16
|
-
-
|
|
17
|
-
- Injection points for a host application's own config cascade and logging.
|
|
15
|
+
- Seeded SQL sampling, PostgreSQL `TABLESAMPLE` and ClickHouse `SAMPLE` for large tables, and `reduce_to_target` to collect about N representative lines from a large source, holding roughly one batch in memory.
|
|
16
|
+
- Injection points for a host application's config cascade and logging.
|
|
18
17
|
|
|
19
|
-
|
|
18
|
+
Install it and reduce a list of lines:
|
|
20
19
|
|
|
21
20
|
```console
|
|
22
21
|
uv add logreducer
|
|
@@ -34,7 +33,7 @@ for line in reduced:
|
|
|
34
33
|
print(line)
|
|
35
34
|
```
|
|
36
35
|
|
|
37
|
-
```
|
|
36
|
+
```console
|
|
38
37
|
540 -> 4
|
|
39
38
|
WARN slow query table=events ms=300
|
|
40
39
|
WARN slow query table=events ms=301
|
|
@@ -44,15 +43,15 @@ INFO GET /health 200 req=1
|
|
|
44
43
|
|
|
45
44
|
From the shell it is `logreducer app.log -o reduced.log`. `level` is `standard`, `enhanced` or `maximum`, trading speed for wider coverage on a 0.5, 1 or 2 GB budget.
|
|
46
45
|
|
|
47
|
-
|
|
46
|
+
Extras add adapters and fuzzy dedup:
|
|
48
47
|
|
|
49
48
|
| Extra | Adds |
|
|
50
49
|
|---|---|
|
|
51
|
-
| `enhanced` | Fuzzy dedup with MinHash LSH
|
|
52
|
-
| `sql` | `SQLSource` over SQLAlchemy, with
|
|
50
|
+
| `enhanced` | Fuzzy dedup with MinHash LSH (the index holds the last `dedup_cache_size` near-unique lines) and faster hashing |
|
|
51
|
+
| `sql` | `SQLSource` over SQLAlchemy, with a DBAPI driver you install |
|
|
53
52
|
| `clickhouse` | `ClickHouseSource` over clickhouse-connect |
|
|
54
53
|
| `kafka` | `KafkaSource` and `KafkaSink` over confluent-kafka |
|
|
55
54
|
|
|
56
55
|
Template mining is derived from [Drain3](https://github.com/logpai/Drain3), MIT licence, with its licence text in the module header.
|
|
57
56
|
|
|
58
|
-
Docs and source are at <https://github.com/hyperi-io/logreducer>.
|
|
57
|
+
Docs and source are at <https://github.com/hyperi-io/logreducer>. PyPI lists the Python floor under Meta. Licensed Apache-2.0: <https://github.com/hyperi-io/logreducer/blob/main/LICENSE>.
|
|
@@ -4,8 +4,8 @@ build-backend = "uv_build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "logreducer"
|
|
7
|
-
version = "3.5.
|
|
8
|
-
description = "
|
|
7
|
+
version = "3.5.7"
|
|
8
|
+
description = "Reduces gigabytes of logs to a small, representative sample, as a CLI or a Python library."
|
|
9
9
|
readme = "docs/pypi.md"
|
|
10
10
|
license = "Apache-2.0"
|
|
11
11
|
license-files = [
|
|
@@ -82,11 +82,8 @@ default = true
|
|
|
82
82
|
module-name = "logreducer"
|
|
83
83
|
module-root = "src"
|
|
84
84
|
|
|
85
|
-
[tool.uv.exclude-newer-package]
|
|
86
|
-
certifi = "2026-10-21T00:00:00Z"
|
|
87
|
-
|
|
88
85
|
[tool.ruff]
|
|
89
|
-
target-version = "
|
|
86
|
+
target-version = "py314"
|
|
90
87
|
line-length = 120
|
|
91
88
|
indent-width = 4
|
|
92
89
|
src = ["src"]
|
|
@@ -187,7 +184,7 @@ skip-magic-trailing-comma = false
|
|
|
187
184
|
line-ending = "auto"
|
|
188
185
|
|
|
189
186
|
[tool.mypy]
|
|
190
|
-
python_version = "3.
|
|
187
|
+
python_version = "3.14"
|
|
191
188
|
ignore_missing_imports = true
|
|
192
189
|
warn_return_any = true
|
|
193
190
|
warn_unused_configs = true
|
|
@@ -216,6 +213,7 @@ markers = [
|
|
|
216
213
|
"""slow: marks tests as slow (deselect with '-m "not slow"')""",
|
|
217
214
|
"integration: marks tests as integration tests",
|
|
218
215
|
]
|
|
216
|
+
shared_service_repo = "logreducer"
|
|
219
217
|
|
|
220
218
|
[tool.coverage.run]
|
|
221
219
|
source = ["logreducer"]
|
|
@@ -263,35 +261,36 @@ skips = [
|
|
|
263
261
|
]
|
|
264
262
|
|
|
265
263
|
[tool.ty.environment]
|
|
266
|
-
python-version = "3.
|
|
264
|
+
python-version = "3.14"
|
|
267
265
|
|
|
268
266
|
[tool.ty.src]
|
|
269
267
|
exclude = [
|
|
270
268
|
"examples/",
|
|
271
269
|
"docs/",
|
|
272
270
|
"scripts/",
|
|
271
|
+
"tests/testdata/build_quiet_golden.py",
|
|
273
272
|
]
|
|
274
273
|
|
|
275
274
|
[tool.vulture]
|
|
276
275
|
min_confidence = 80
|
|
277
276
|
|
|
278
277
|
[tool.vermin]
|
|
279
|
-
targets = ["3.
|
|
278
|
+
targets = ["3.14"]
|
|
280
279
|
no_tips = true
|
|
281
280
|
|
|
282
281
|
[tool.hatch.build.targets.sdist]
|
|
283
282
|
exclude = [
|
|
284
283
|
"/CURSOR.md",
|
|
284
|
+
"/.cursor",
|
|
285
285
|
"/CLAUDE.md",
|
|
286
|
-
"/STATE.md",
|
|
287
|
-
"/ci",
|
|
288
286
|
"/.github/copilot-instructions.md",
|
|
287
|
+
"/ci",
|
|
288
|
+
"/STATE.md",
|
|
289
289
|
"/.claude",
|
|
290
290
|
"/hyperi-ai",
|
|
291
|
-
"
|
|
291
|
+
"/GEMINI.md",
|
|
292
292
|
"/.gemini",
|
|
293
293
|
"/.windsurf",
|
|
294
|
-
"/GEMINI.md",
|
|
295
294
|
]
|
|
296
295
|
|
|
297
296
|
[dependency-groups]
|
|
@@ -311,7 +310,8 @@ dev = [
|
|
|
311
310
|
"sqlalchemy>=2.1.3",
|
|
312
311
|
"clickhouse-connect>=1.9.0",
|
|
313
312
|
"confluent-kafka>=2.15.1",
|
|
314
|
-
"
|
|
313
|
+
"scalo>=2.32.4",
|
|
314
|
+
"testcontainers[postgres,mysql]>=4.15.0",
|
|
315
315
|
"psycopg[binary]>=3.2",
|
|
316
316
|
"pymysql>=1.1.0",
|
|
317
317
|
"python-dotenv>=1.0.0",
|
|
@@ -6,14 +6,14 @@ build-backend = "uv_build"
|
|
|
6
6
|
|
|
7
7
|
[project]
|
|
8
8
|
name = "logreducer"
|
|
9
|
-
version = "3.5.
|
|
9
|
+
version = "3.5.7"
|
|
10
10
|
authors = [
|
|
11
11
|
{ name = "HyperI Team", email = "dev@hyperi.io" },
|
|
12
12
|
]
|
|
13
13
|
maintainers = [
|
|
14
14
|
{ name = "HyperI Team", email = "dev@hyperi.io" },
|
|
15
15
|
]
|
|
16
|
-
description = "
|
|
16
|
+
description = "Reduces gigabytes of logs to a small, representative sample, as a CLI or a Python library."
|
|
17
17
|
readme = "docs/pypi.md"
|
|
18
18
|
license = "Apache-2.0"
|
|
19
19
|
license-files = [
|
|
@@ -86,11 +86,8 @@ index = [
|
|
|
86
86
|
module-name = "logreducer"
|
|
87
87
|
module-root = "src"
|
|
88
88
|
|
|
89
|
-
[tool.uv.exclude-newer-package]
|
|
90
|
-
certifi = "2026-10-21T00:00:00Z"
|
|
91
|
-
|
|
92
89
|
[tool.ruff]
|
|
93
|
-
target-version = "
|
|
90
|
+
target-version = "py314"
|
|
94
91
|
line-length = 120
|
|
95
92
|
indent-width = 4
|
|
96
93
|
src = [
|
|
@@ -209,7 +206,7 @@ skip-magic-trailing-comma = false
|
|
|
209
206
|
line-ending = "auto"
|
|
210
207
|
|
|
211
208
|
[tool.mypy]
|
|
212
|
-
python_version = "3.
|
|
209
|
+
python_version = "3.14"
|
|
213
210
|
ignore_missing_imports = true
|
|
214
211
|
warn_return_any = true
|
|
215
212
|
warn_unused_configs = true
|
|
@@ -244,6 +241,7 @@ markers = [
|
|
|
244
241
|
"slow: marks tests as slow (deselect with '-m \"not slow\"')",
|
|
245
242
|
"integration: marks tests as integration tests",
|
|
246
243
|
]
|
|
244
|
+
shared_service_repo = "logreducer"
|
|
247
245
|
|
|
248
246
|
[tool.coverage.run]
|
|
249
247
|
source = [
|
|
@@ -293,13 +291,14 @@ skips = [
|
|
|
293
291
|
]
|
|
294
292
|
|
|
295
293
|
[tool.ty.environment]
|
|
296
|
-
python-version = "3.
|
|
294
|
+
python-version = "3.14"
|
|
297
295
|
|
|
298
296
|
[tool.ty.src]
|
|
299
297
|
exclude = [
|
|
300
298
|
"examples/",
|
|
301
299
|
"docs/",
|
|
302
300
|
"scripts/",
|
|
301
|
+
"tests/testdata/build_quiet_golden.py",
|
|
303
302
|
]
|
|
304
303
|
|
|
305
304
|
[tool.vulture]
|
|
@@ -307,23 +306,23 @@ min_confidence = 80
|
|
|
307
306
|
|
|
308
307
|
[tool.vermin]
|
|
309
308
|
targets = [
|
|
310
|
-
"3.
|
|
309
|
+
"3.14",
|
|
311
310
|
]
|
|
312
311
|
no_tips = true
|
|
313
312
|
|
|
314
313
|
[tool.hatch.build.targets.sdist]
|
|
315
314
|
exclude = [
|
|
316
315
|
"/CURSOR.md",
|
|
316
|
+
"/.cursor",
|
|
317
317
|
"/CLAUDE.md",
|
|
318
|
-
"/STATE.md",
|
|
319
|
-
"/ci",
|
|
320
318
|
"/.github/copilot-instructions.md",
|
|
319
|
+
"/ci",
|
|
320
|
+
"/STATE.md",
|
|
321
321
|
"/.claude",
|
|
322
322
|
"/hyperi-ai",
|
|
323
|
-
"
|
|
323
|
+
"/GEMINI.md",
|
|
324
324
|
"/.gemini",
|
|
325
325
|
"/.windsurf",
|
|
326
|
-
"/GEMINI.md",
|
|
327
326
|
]
|
|
328
327
|
|
|
329
328
|
[dependency-groups]
|
|
@@ -343,7 +342,8 @@ dev = [
|
|
|
343
342
|
"sqlalchemy>=2.1.3",
|
|
344
343
|
"clickhouse-connect>=1.9.0",
|
|
345
344
|
"confluent-kafka>=2.15.1",
|
|
346
|
-
"
|
|
345
|
+
"scalo>=2.32.4",
|
|
346
|
+
"testcontainers[postgres,mysql]>=4.15.0",
|
|
347
347
|
"psycopg[binary]>=3.2",
|
|
348
348
|
"pymysql>=1.1.0",
|
|
349
349
|
"python-dotenv>=1.0.0",
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Anomaly detection utilities."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
logger = logging.getLogger(__name__)
|
|
9
|
+
|
|
10
|
+
# Fewer lines than this are returned unscored, all of them normal.
|
|
11
|
+
MIN_SCORED_LINES = 10
|
|
12
|
+
|
|
13
|
+
# Hashed n-gram columns. Hashing keeps no vocabulary, so memory follows the
|
|
14
|
+
# line count, not the number of distinct terms the lines carry.
|
|
15
|
+
HASHED_FEATURES = 2**20
|
|
16
|
+
|
|
17
|
+
# Scored columns: the most frequent hashed terms in at least two lines and at most this share of them.
|
|
18
|
+
MAX_SCORED_FEATURES = 1000
|
|
19
|
+
MAX_DOC_SHARE = 0.9
|
|
20
|
+
|
|
21
|
+
# Try optional imports
|
|
22
|
+
try:
|
|
23
|
+
from sklearn.ensemble import IsolationForest
|
|
24
|
+
from sklearn.feature_extraction.text import HashingVectorizer, TfidfTransformer
|
|
25
|
+
|
|
26
|
+
SKLEARN_AVAILABLE = True
|
|
27
|
+
except ImportError:
|
|
28
|
+
SKLEARN_AVAILABLE = False
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class AnomalyDetector:
|
|
32
|
+
"""Detect anomalous log lines."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, contamination: float = 0.1):
|
|
35
|
+
self.contamination = contamination
|
|
36
|
+
self.enabled = SKLEARN_AVAILABLE
|
|
37
|
+
|
|
38
|
+
if not self.enabled:
|
|
39
|
+
logger.warning("scikit-learn not available, anomaly detection disabled")
|
|
40
|
+
|
|
41
|
+
def detect_anomalies(self, lines: list[str]) -> tuple[list[str], list[str]]:
|
|
42
|
+
"""Separate anomalous and normal lines.
|
|
43
|
+
|
|
44
|
+
Returns:
|
|
45
|
+
(anomalous_lines, normal_lines)
|
|
46
|
+
"""
|
|
47
|
+
if not self.enabled or len(lines) < MIN_SCORED_LINES:
|
|
48
|
+
return [], lines
|
|
49
|
+
|
|
50
|
+
# The matrix stays sparse: densified it is lines x HASHED_FEATURES x 8 bytes.
|
|
51
|
+
counts = HashingVectorizer(
|
|
52
|
+
n_features=HASHED_FEATURES, ngram_range=(1, 3), alternate_sign=False, norm=None
|
|
53
|
+
).transform(lines)
|
|
54
|
+
columns = _scored_columns(counts, len(lines))
|
|
55
|
+
if columns.size == 0:
|
|
56
|
+
# No term is shared by enough lines to score, so every line is normal.
|
|
57
|
+
return [], lines
|
|
58
|
+
X = TfidfTransformer().fit_transform(counts[:, columns])
|
|
59
|
+
|
|
60
|
+
iso_forest = IsolationForest(contamination=self.contamination, random_state=42, n_estimators=100)
|
|
61
|
+
labels = iso_forest.fit_predict(X)
|
|
62
|
+
scores = iso_forest.score_samples(X)
|
|
63
|
+
|
|
64
|
+
# One pass: split normal vs anomalous, collecting scores for the latter.
|
|
65
|
+
normal: list[str] = []
|
|
66
|
+
anomaly_with_scores: list[tuple[str, float]] = []
|
|
67
|
+
for line, label, score in zip(lines, labels, scores, strict=False):
|
|
68
|
+
if label == -1:
|
|
69
|
+
anomaly_with_scores.append((line, score))
|
|
70
|
+
else:
|
|
71
|
+
normal.append(line)
|
|
72
|
+
|
|
73
|
+
# Most anomalous first (IsolationForest scores: lower = more anomalous).
|
|
74
|
+
anomaly_with_scores.sort(key=lambda pair: pair[1])
|
|
75
|
+
anomalous = [line for line, _ in anomaly_with_scores]
|
|
76
|
+
|
|
77
|
+
logger.info(f"Found {len(anomalous)} anomalies out of {len(lines)} lines")
|
|
78
|
+
|
|
79
|
+
return anomalous, normal
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _scored_columns(counts: Any, line_count: int) -> np.ndarray:
|
|
83
|
+
"""Pick the hashed columns to score, as a vocabulary with ``min_df``, ``max_df`` and ``max_features`` would.
|
|
84
|
+
|
|
85
|
+
A term in a single line, a request id say, isolates that line in one split, so it
|
|
86
|
+
says nothing about how unusual the line is. A term in nearly every line separates none.
|
|
87
|
+
"""
|
|
88
|
+
min_lines = 2 if line_count > 100 else 1
|
|
89
|
+
doc_freq = counts.getnnz(axis=0)
|
|
90
|
+
shared = np.flatnonzero((doc_freq >= min_lines) & (doc_freq <= MAX_DOC_SHARE * line_count))
|
|
91
|
+
limit = min(MAX_SCORED_FEATURES, line_count // 10)
|
|
92
|
+
if shared.size <= limit:
|
|
93
|
+
return shared
|
|
94
|
+
term_freq = np.asarray(counts[:, shared].sum(axis=0)).ravel()
|
|
95
|
+
return np.sort(shared[np.argsort(-term_freq, kind="stable")[:limit]])
|
|
@@ -14,6 +14,7 @@ nothing. Built on typer.
|
|
|
14
14
|
"""
|
|
15
15
|
|
|
16
16
|
import json
|
|
17
|
+
import os
|
|
17
18
|
import sys
|
|
18
19
|
from typing import Any
|
|
19
20
|
|
|
@@ -88,7 +89,11 @@ def _reduce(
|
|
|
88
89
|
pretty_json: bool = typer.Option(False, "--pretty-json", help="Pretty-print JSON output"),
|
|
89
90
|
level: str = typer.Option("standard", "--level", "-l", help="Processing level: standard, enhanced, maximum"),
|
|
90
91
|
mode: str = typer.Option("pattern", "--mode", "-m", help="Processing mode: pattern, anomaly, temporal, hybrid"),
|
|
91
|
-
dsn: str | None = typer.Option(
|
|
92
|
+
dsn: str | None = typer.Option(
|
|
93
|
+
None,
|
|
94
|
+
"--dsn",
|
|
95
|
+
help="Source DSN: postgresql://, clickhouse://, kafka://, ... With no file or --dsn, read from LOGREDUCER_DSN",
|
|
96
|
+
),
|
|
92
97
|
query: str | None = typer.Option(None, "--query", help="SQL SELECT (first column is the log line) for --dsn"),
|
|
93
98
|
topic: str | None = typer.Option(None, "--topic", help="Kafka topic (with a kafka:// --dsn)"),
|
|
94
99
|
group: str | None = typer.Option(None, "--group", help="Kafka consumer group (with a kafka:// --dsn)"),
|
|
@@ -118,6 +123,10 @@ def _reduce(
|
|
|
118
123
|
),
|
|
119
124
|
) -> None:
|
|
120
125
|
"""Reduce a log source to a representative sample."""
|
|
126
|
+
# The environment keeps a password off the command line, and a named file or --dsn wins over it.
|
|
127
|
+
if dsn is None and input_file is None:
|
|
128
|
+
dsn = os.environ.get("LOGREDUCER_DSN") or None
|
|
129
|
+
|
|
121
130
|
# Build reducer config overrides, dropping unset values.
|
|
122
131
|
overrides: dict[str, Any] = {
|
|
123
132
|
"max_memory_gb": max_memory,
|
|
@@ -189,7 +198,7 @@ def _reduce(
|
|
|
189
198
|
else:
|
|
190
199
|
_err("Error: provide a log file, or --dsn with --query (SQL/ClickHouse) or --topic/--group (Kafka)")
|
|
191
200
|
raise typer.Exit(1)
|
|
192
|
-
except
|
|
201
|
+
except typer.Exit, typer.BadParameter:
|
|
193
202
|
raise # our control-flow exit / typer usage errors - let typer format them
|
|
194
203
|
except KeyboardInterrupt:
|
|
195
204
|
_err("Processing interrupted by user")
|
|
@@ -258,7 +267,9 @@ def _run_target(
|
|
|
258
267
|
elif input_file:
|
|
259
268
|
from .sources import FileSource
|
|
260
269
|
|
|
261
|
-
source = FileSource(
|
|
270
|
+
source = FileSource(
|
|
271
|
+
input_file, max_memory_gb=reducer.config.max_memory_gb, max_severe_shapes=reducer.max_severe_shapes
|
|
272
|
+
)
|
|
262
273
|
else:
|
|
263
274
|
_err("Error: --target-rows needs a log file, or --dsn with --query (SQL/ClickHouse)")
|
|
264
275
|
raise typer.Exit(1)
|
|
@@ -276,7 +287,7 @@ def _run_target(
|
|
|
276
287
|
close = getattr(source, "close", None)
|
|
277
288
|
if callable(close):
|
|
278
289
|
close()
|
|
279
|
-
except
|
|
290
|
+
except typer.Exit, typer.BadParameter:
|
|
280
291
|
raise
|
|
281
292
|
except KeyboardInterrupt:
|
|
282
293
|
_err("Processing interrupted by user")
|
|
@@ -47,6 +47,7 @@ class BigDialConfig:
|
|
|
47
47
|
# measured reductions use tens of MB, so the default is deliberately low
|
|
48
48
|
# and container-friendly.
|
|
49
49
|
max_memory_gb: float = 1.0
|
|
50
|
+
# Lines exact dedup remembers, and lines the fuzzy index holds. Both drop the oldest first.
|
|
50
51
|
dedup_cache_size: int = 100000
|
|
51
52
|
|
|
52
53
|
# Speed Control
|
|
@@ -60,10 +61,10 @@ class BigDialConfig:
|
|
|
60
61
|
# Bound the Drain3 template store (LRU-evict beyond this many templates).
|
|
61
62
|
# None = unbounded (the store then grows with distinct templates).
|
|
62
63
|
max_clusters: int | None = 10_000
|
|
63
|
-
#
|
|
64
|
-
|
|
65
|
-
#
|
|
66
|
-
anomaly_max_rows: int | None =
|
|
64
|
+
# Templates a line is compared with at its leaf, the last to take a line. None = all.
|
|
65
|
+
max_leaf_clusters: int | None = 128
|
|
66
|
+
# Rows anomaly detection scores, reservoir-sampled at some cost in recall. None = all.
|
|
67
|
+
anomaly_max_rows: int | None = 10_000
|
|
67
68
|
# Typed Drain3 masking: replace well-known value shapes (IPv4/IPv6, MAC,
|
|
68
69
|
# UUID, hex tokens, numbers) with typed template slots (<IP>, <NUM>, ...)
|
|
69
70
|
# before clustering, instead of the bare <*>. Opt-in: masking normalises
|
|
@@ -77,6 +78,8 @@ class BigDialConfig:
|
|
|
77
78
|
# Sampling Control
|
|
78
79
|
max_patterns: int = 1000
|
|
79
80
|
examples_per_pattern: int = 3
|
|
81
|
+
# Severe lines kept, one per shape, outside max_patterns. None = max_patterns.
|
|
82
|
+
max_severe_shapes: int | None = None
|
|
80
83
|
|
|
81
84
|
# Logging Control
|
|
82
85
|
enable_logging: bool = False # Logging disabled by default
|
|
@@ -101,7 +104,7 @@ class BigDialConfig:
|
|
|
101
104
|
self.max_memory_gb = clamped
|
|
102
105
|
|
|
103
106
|
@classmethod
|
|
104
|
-
def from_env(cls, *prefixes: str) ->
|
|
107
|
+
def from_env(cls, *prefixes: str) -> BigDialConfig:
|
|
105
108
|
"""Build a config from environment variables, cascade-aware.
|
|
106
109
|
|
|
107
110
|
``from_env()`` reads ``LOGREDUCER_<FIELD>`` (upper-cased field names,
|
|
@@ -137,7 +140,7 @@ def validate_config(config: BigDialConfig) -> None:
|
|
|
137
140
|
for name in ("dedup_cache_size", "temporal_window_minutes", "max_patterns", "examples_per_pattern"):
|
|
138
141
|
if getattr(config, name) < 1:
|
|
139
142
|
raise ValueError(f"{name} must be at least 1, got {getattr(config, name)!r}")
|
|
140
|
-
for name in ("max_clusters", "anomaly_max_rows"):
|
|
143
|
+
for name in ("max_clusters", "max_leaf_clusters", "anomaly_max_rows", "max_severe_shapes"):
|
|
141
144
|
value = getattr(config, name)
|
|
142
145
|
if value is not None and value < 1:
|
|
143
146
|
raise ValueError(f"{name} must be at least 1 or None, got {value!r}")
|