logreducer 3.5.6__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.6 → logreducer-3.5.7}/PKG-INFO +12 -13
- {logreducer-3.5.6 → logreducer-3.5.7}/docs/pypi.md +10 -11
- {logreducer-3.5.6 → logreducer-3.5.7}/pyproject.toml +9 -12
- {logreducer-3.5.6 → logreducer-3.5.7}/pyproject.toml.orig +9 -12
- {logreducer-3.5.6 → logreducer-3.5.7}/src/logreducer/anomaly.py +36 -18
- {logreducer-3.5.6 → logreducer-3.5.7}/src/logreducer/cli.py +13 -2
- {logreducer-3.5.6 → logreducer-3.5.7}/src/logreducer/config.py +7 -5
- {logreducer-3.5.6 → logreducer-3.5.7}/src/logreducer/core.py +33 -12
- {logreducer-3.5.6 → logreducer-3.5.7}/src/logreducer/kafka.py +25 -11
- {logreducer-3.5.6 → logreducer-3.5.7}/src/logreducer/logging_config.py +3 -2
- {logreducer-3.5.6 → logreducer-3.5.7}/src/logreducer/memory.py +1 -1
- {logreducer-3.5.6 → logreducer-3.5.7}/src/logreducer/patterns.py +16 -4
- {logreducer-3.5.6 → logreducer-3.5.7}/src/logreducer/sources.py +8 -3
- {logreducer-3.5.6 → logreducer-3.5.7}/src/logreducer/template_mining.py +62 -9
- {logreducer-3.5.6 → logreducer-3.5.7}/src/logreducer/temporal.py +12 -5
- {logreducer-3.5.6 → logreducer-3.5.7}/LICENSE +0 -0
- {logreducer-3.5.6 → logreducer-3.5.7}/NOTICE +0 -0
- {logreducer-3.5.6 → logreducer-3.5.7}/src/logreducer/__init__.py +0 -0
- {logreducer-3.5.6 → logreducer-3.5.7}/src/logreducer/clickhouse.py +0 -0
- {logreducer-3.5.6 → logreducer-3.5.7}/src/logreducer/py.typed +0 -0
- {logreducer-3.5.6 → logreducer-3.5.7}/src/logreducer/sampling.py +0 -0
- {logreducer-3.5.6 → logreducer-3.5.7}/src/logreducer/sinks.py +0 -0
- {logreducer-3.5.6 → logreducer-3.5.7}/src/logreducer/sql.py +0 -0
- {logreducer-3.5.6 → logreducer-3.5.7}/src/logreducer/target.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, fuzzy index and template store, so memory does not grow with the line count
|
|
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
|
-
- Lines naming ERROR, FATAL or CRITICAL as a whole word, in any case,
|
|
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, fuzzy index and template store, so memory does not grow with the line count
|
|
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
|
-
- Lines naming ERROR, FATAL or CRITICAL as a whole word, in any case,
|
|
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,9 +82,6 @@ default = true
|
|
|
82
82
|
module-name = "logreducer"
|
|
83
83
|
module-root = "src"
|
|
84
84
|
|
|
85
|
-
[tool.uv.exclude-newer-package]
|
|
86
|
-
scalo = "2026-11-01T06:00:00Z"
|
|
87
|
-
|
|
88
85
|
[tool.ruff]
|
|
89
86
|
target-version = "py314"
|
|
90
87
|
line-length = 120
|
|
@@ -283,17 +280,17 @@ no_tips = true
|
|
|
283
280
|
|
|
284
281
|
[tool.hatch.build.targets.sdist]
|
|
285
282
|
exclude = [
|
|
286
|
-
"/.claude",
|
|
287
|
-
"/GEMINI.md",
|
|
288
283
|
"/CURSOR.md",
|
|
289
|
-
"/.
|
|
284
|
+
"/.cursor",
|
|
290
285
|
"/CLAUDE.md",
|
|
291
|
-
"/.gemini",
|
|
292
|
-
"/hyperi-ai",
|
|
293
286
|
"/.github/copilot-instructions.md",
|
|
294
|
-
"/.cursor",
|
|
295
|
-
"/STATE.md",
|
|
296
287
|
"/ci",
|
|
288
|
+
"/STATE.md",
|
|
289
|
+
"/.claude",
|
|
290
|
+
"/hyperi-ai",
|
|
291
|
+
"/GEMINI.md",
|
|
292
|
+
"/.gemini",
|
|
293
|
+
"/.windsurf",
|
|
297
294
|
]
|
|
298
295
|
|
|
299
296
|
[dependency-groups]
|
|
@@ -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,9 +86,6 @@ index = [
|
|
|
86
86
|
module-name = "logreducer"
|
|
87
87
|
module-root = "src"
|
|
88
88
|
|
|
89
|
-
[tool.uv.exclude-newer-package]
|
|
90
|
-
scalo = "2026-11-01T06:00:00Z"
|
|
91
|
-
|
|
92
89
|
[tool.ruff]
|
|
93
90
|
target-version = "py314"
|
|
94
91
|
line-length = 120
|
|
@@ -315,17 +312,17 @@ no_tips = true
|
|
|
315
312
|
|
|
316
313
|
[tool.hatch.build.targets.sdist]
|
|
317
314
|
exclude = [
|
|
318
|
-
"/.claude",
|
|
319
|
-
"/GEMINI.md",
|
|
320
315
|
"/CURSOR.md",
|
|
321
|
-
"/.
|
|
316
|
+
"/.cursor",
|
|
322
317
|
"/CLAUDE.md",
|
|
323
|
-
"/.gemini",
|
|
324
|
-
"/hyperi-ai",
|
|
325
318
|
"/.github/copilot-instructions.md",
|
|
326
|
-
"/.cursor",
|
|
327
|
-
"/STATE.md",
|
|
328
319
|
"/ci",
|
|
320
|
+
"/STATE.md",
|
|
321
|
+
"/.claude",
|
|
322
|
+
"/hyperi-ai",
|
|
323
|
+
"/GEMINI.md",
|
|
324
|
+
"/.gemini",
|
|
325
|
+
"/.windsurf",
|
|
329
326
|
]
|
|
330
327
|
|
|
331
328
|
[dependency-groups]
|
|
@@ -1,16 +1,27 @@
|
|
|
1
1
|
"""Anomaly detection utilities."""
|
|
2
2
|
|
|
3
3
|
import logging
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
4
7
|
|
|
5
8
|
logger = logging.getLogger(__name__)
|
|
6
9
|
|
|
7
10
|
# Fewer lines than this are returned unscored, all of them normal.
|
|
8
11
|
MIN_SCORED_LINES = 10
|
|
9
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
|
+
|
|
10
21
|
# Try optional imports
|
|
11
22
|
try:
|
|
12
23
|
from sklearn.ensemble import IsolationForest
|
|
13
|
-
from sklearn.feature_extraction.text import
|
|
24
|
+
from sklearn.feature_extraction.text import HashingVectorizer, TfidfTransformer
|
|
14
25
|
|
|
15
26
|
SKLEARN_AVAILABLE = True
|
|
16
27
|
except ImportError:
|
|
@@ -36,24 +47,15 @@ class AnomalyDetector:
|
|
|
36
47
|
if not self.enabled or len(lines) < MIN_SCORED_LINES:
|
|
37
48
|
return [], lines
|
|
38
49
|
|
|
39
|
-
#
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
try:
|
|
48
|
-
# Keep the TF-IDF matrix SPARSE - IsolationForest accepts sparse
|
|
49
|
-
# input directly. Densifying (.toarray()) would allocate
|
|
50
|
-
# n_lines x n_features x 8 bytes, which dwarfs the sparse matrix and
|
|
51
|
-
# can blow the memory budget on a large unique-line set.
|
|
52
|
-
X = vectorizer.fit_transform(lines)
|
|
53
|
-
except ValueError:
|
|
54
|
-
# Empty vocabulary (every term filtered by min_df/max_df) - nothing
|
|
55
|
-
# to score, so treat all lines as normal rather than failing.
|
|
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.
|
|
56
57
|
return [], lines
|
|
58
|
+
X = TfidfTransformer().fit_transform(counts[:, columns])
|
|
57
59
|
|
|
58
60
|
iso_forest = IsolationForest(contamination=self.contamination, random_state=42, n_estimators=100)
|
|
59
61
|
labels = iso_forest.fit_predict(X)
|
|
@@ -75,3 +77,19 @@ class AnomalyDetector:
|
|
|
75
77
|
logger.info(f"Found {len(anomalous)} anomalies out of {len(lines)} lines")
|
|
76
78
|
|
|
77
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,
|
|
@@ -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)
|
|
@@ -61,10 +61,10 @@ class BigDialConfig:
|
|
|
61
61
|
# Bound the Drain3 template store (LRU-evict beyond this many templates).
|
|
62
62
|
# None = unbounded (the store then grows with distinct templates).
|
|
63
63
|
max_clusters: int | None = 10_000
|
|
64
|
-
#
|
|
65
|
-
|
|
66
|
-
#
|
|
67
|
-
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
|
|
68
68
|
# Typed Drain3 masking: replace well-known value shapes (IPv4/IPv6, MAC,
|
|
69
69
|
# UUID, hex tokens, numbers) with typed template slots (<IP>, <NUM>, ...)
|
|
70
70
|
# before clustering, instead of the bare <*>. Opt-in: masking normalises
|
|
@@ -78,6 +78,8 @@ class BigDialConfig:
|
|
|
78
78
|
# Sampling Control
|
|
79
79
|
max_patterns: int = 1000
|
|
80
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
|
|
81
83
|
|
|
82
84
|
# Logging Control
|
|
83
85
|
enable_logging: bool = False # Logging disabled by default
|
|
@@ -138,7 +140,7 @@ def validate_config(config: BigDialConfig) -> None:
|
|
|
138
140
|
for name in ("dedup_cache_size", "temporal_window_minutes", "max_patterns", "examples_per_pattern"):
|
|
139
141
|
if getattr(config, name) < 1:
|
|
140
142
|
raise ValueError(f"{name} must be at least 1, got {getattr(config, name)!r}")
|
|
141
|
-
for name in ("max_clusters", "anomaly_max_rows"):
|
|
143
|
+
for name in ("max_clusters", "max_leaf_clusters", "anomaly_max_rows", "max_severe_shapes"):
|
|
142
144
|
value = getattr(config, name)
|
|
143
145
|
if value is not None and value < 1:
|
|
144
146
|
raise ValueError(f"{name} must be at least 1 or None, got {value!r}")
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import json
|
|
4
4
|
import os
|
|
5
5
|
import random
|
|
6
|
+
import reprlib
|
|
6
7
|
import time
|
|
7
8
|
from collections.abc import Iterable
|
|
8
9
|
from dataclasses import replace
|
|
@@ -21,6 +22,9 @@ from .sinks import Sink
|
|
|
21
22
|
from .sources import FileSource, Source
|
|
22
23
|
from .temporal import TemporalProcessor
|
|
23
24
|
|
|
25
|
+
# Names a source in stats and logs without copying the lines of a list source.
|
|
26
|
+
_SOURCE_LABEL = reprlib.Repr(maxother=200)
|
|
27
|
+
|
|
24
28
|
|
|
25
29
|
class LogReducer:
|
|
26
30
|
"""Main log reduction class.
|
|
@@ -49,7 +53,7 @@ class LogReducer:
|
|
|
49
53
|
config: A fully-built BigDialConfig to use INSTEAD of the level
|
|
50
54
|
preset - the injection seam for a host application that owns
|
|
51
55
|
its own config cascade (build the config however you like and
|
|
52
|
-
hand it over
|
|
56
|
+
hand it over, and kwargs still apply on top). Copied, so the
|
|
53
57
|
caller's object is never mutated. ``level`` then only selects
|
|
54
58
|
the fuzzy-dedup gate, not preset values.
|
|
55
59
|
**kwargs: Additional config overrides
|
|
@@ -93,7 +97,6 @@ class LogReducer:
|
|
|
93
97
|
# Get logger for this module
|
|
94
98
|
self.logger = get_logger("logreducer.core")
|
|
95
99
|
|
|
96
|
-
# Initialize components
|
|
97
100
|
self.memory_monitor = MemoryMonitor(self.config.max_memory_gb)
|
|
98
101
|
|
|
99
102
|
if mode in [ProcessingMode.ANOMALY, ProcessingMode.HYBRID]:
|
|
@@ -127,7 +130,9 @@ class LogReducer:
|
|
|
127
130
|
else:
|
|
128
131
|
self.fuzzy_dedup = None
|
|
129
132
|
if self.mode in [ProcessingMode.TEMPORAL, ProcessingMode.HYBRID]:
|
|
130
|
-
self.temporal_processor = TemporalProcessor(
|
|
133
|
+
self.temporal_processor = TemporalProcessor(
|
|
134
|
+
self.config.temporal_window_minutes, self.config.max_clusters, self.config.max_leaf_clusters
|
|
135
|
+
)
|
|
131
136
|
else:
|
|
132
137
|
self.temporal_processor = None
|
|
133
138
|
|
|
@@ -213,20 +218,30 @@ class LogReducer:
|
|
|
213
218
|
# Count input lines for the reduction ratio (one pass over the source).
|
|
214
219
|
# Note: a size-sampled FileSource yields its sampled line count, so for
|
|
215
220
|
# very large files the ratio and input_lines stat are approximate.
|
|
216
|
-
|
|
221
|
+
severe_cap = self.max_severe_shapes
|
|
222
|
+
# A FileSource collects severe shapes as it reads, so it takes this run's cap first.
|
|
223
|
+
if isinstance(source, FileSource):
|
|
224
|
+
own_cap = source.max_severe_shapes
|
|
225
|
+
if own_cap is None or own_cap > severe_cap:
|
|
226
|
+
source.max_severe_shapes = severe_cap
|
|
227
|
+
shapes = SevereShapes(severe_cap)
|
|
217
228
|
input_lines = 0
|
|
218
229
|
for line in source:
|
|
219
230
|
input_lines += 1
|
|
220
231
|
shapes.add(line)
|
|
221
232
|
# A FileSource taps its own reads, which see the lines it samples away.
|
|
222
233
|
shapes = getattr(source, "severe_shapes", shapes)
|
|
234
|
+
severe_lines = shapes.lines
|
|
235
|
+
severe_dropped = shapes.dropped
|
|
223
236
|
|
|
224
237
|
size_bytes = getattr(source, "size_bytes", None)
|
|
225
238
|
file_size_mb = size_bytes / (1024 * 1024) if size_bytes else None
|
|
239
|
+
input_path = getattr(source, "path", None)
|
|
240
|
+
input_label = str(input_path) if input_path is not None else _SOURCE_LABEL.repr(source)
|
|
226
241
|
|
|
227
242
|
if self.config.enable_logging:
|
|
228
243
|
where = f"{file_size_mb:.1f} MB" if file_size_mb is not None else f"{input_lines:,} lines"
|
|
229
|
-
self.logger.info(f"Reducing {
|
|
244
|
+
self.logger.info(f"Reducing {input_label} ({where})")
|
|
230
245
|
self.logger.info(f"Mode: {self.mode.value}, Level: {self.level.value}")
|
|
231
246
|
self.logger.info(f"Memory limit: {self.config.max_memory_gb:.1f} GB")
|
|
232
247
|
|
|
@@ -240,21 +255,20 @@ class LogReducer:
|
|
|
240
255
|
else: # HYBRID
|
|
241
256
|
result_lines = self._process_hybrid_mode(source)
|
|
242
257
|
|
|
243
|
-
# Modes return quiet lines under their caps. Severe lines are one per shape,
|
|
244
|
-
|
|
245
|
-
result_lines = shapes.lines + result_lines
|
|
258
|
+
# Modes return quiet lines under their caps. Severe lines are one per shape, under max_severe_shapes.
|
|
259
|
+
result_lines = severe_lines + result_lines
|
|
246
260
|
|
|
247
261
|
# Calculate stats
|
|
248
262
|
processing_time = time.time() - start_time
|
|
249
263
|
output_lines = len(result_lines)
|
|
250
264
|
reduction_percent = (1 - output_lines / max(input_lines, 1)) * 100 if input_lines > 0 else 0
|
|
251
|
-
input_label = getattr(source, "path", None)
|
|
252
265
|
|
|
253
266
|
self.stats = {
|
|
254
|
-
"input_file":
|
|
267
|
+
"input_file": input_label,
|
|
255
268
|
"input_lines": input_lines,
|
|
256
269
|
"input_size_mb": file_size_mb,
|
|
257
270
|
"output_lines": output_lines,
|
|
271
|
+
"severe_dropped": severe_dropped,
|
|
258
272
|
"reduction_percent": reduction_percent,
|
|
259
273
|
"processing_time_seconds": processing_time,
|
|
260
274
|
"processing_rate_mb_per_sec": (
|
|
@@ -324,9 +338,17 @@ class LogReducer:
|
|
|
324
338
|
"""
|
|
325
339
|
if not os.path.exists(input_file):
|
|
326
340
|
raise FileNotFoundError(f"File not found: {input_file}")
|
|
327
|
-
source = FileSource(
|
|
341
|
+
source = FileSource(
|
|
342
|
+
input_file, max_memory_gb=self.config.max_memory_gb, max_severe_shapes=self.max_severe_shapes
|
|
343
|
+
)
|
|
328
344
|
return self.reduce(source, output_file=output_file, return_metadata=return_metadata)
|
|
329
345
|
|
|
346
|
+
@property
|
|
347
|
+
def max_severe_shapes(self) -> int:
|
|
348
|
+
"""Severe lines a run keeps, one per shape: ``max_severe_shapes``, else ``max_patterns``."""
|
|
349
|
+
configured = self.config.max_severe_shapes
|
|
350
|
+
return configured if configured is not None else self.config.max_patterns
|
|
351
|
+
|
|
330
352
|
def _process_pattern_mode(self, source: Source) -> list[str]:
|
|
331
353
|
"""Process using pattern extraction, streaming end to end.
|
|
332
354
|
|
|
@@ -433,7 +455,6 @@ class LogReducer:
|
|
|
433
455
|
if self.config.enable_logging:
|
|
434
456
|
self.logger.info("Hybrid mode: combining pattern and anomaly detection")
|
|
435
457
|
|
|
436
|
-
# Get patterns
|
|
437
458
|
pattern_lines = self._process_pattern_mode(source)
|
|
438
459
|
|
|
439
460
|
# Get anomalies if available
|
|
@@ -29,6 +29,7 @@ Install: ``pip install 'logreducer[kafka]'``.
|
|
|
29
29
|
|
|
30
30
|
import importlib.util
|
|
31
31
|
import time
|
|
32
|
+
import warnings
|
|
32
33
|
from collections.abc import Iterable, Iterator
|
|
33
34
|
from typing import Any, Self
|
|
34
35
|
|
|
@@ -57,15 +58,13 @@ CONSUMER_DEFAULTS: dict[str, Any] = {
|
|
|
57
58
|
"enable.partition.eof": True,
|
|
58
59
|
}
|
|
59
60
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
}
|
|
68
|
-
)
|
|
61
|
+
# A key is a credential when it is listed, ends in one of the suffixes, or holds one of the parts.
|
|
62
|
+
_CREDENTIAL_KEYS = frozenset({"sasl.username"})
|
|
63
|
+
_CREDENTIAL_SUFFIXES = (".password", ".secret", ".pem")
|
|
64
|
+
_CREDENTIAL_PARTS = ("oauthbearer.config", "private.key")
|
|
65
|
+
|
|
66
|
+
# Set once a config has turned TLS verification off, so the warning shows once per process.
|
|
67
|
+
_warned_unverified = False
|
|
69
68
|
|
|
70
69
|
_INSTALL_HINT = (
|
|
71
70
|
"logreducer's Kafka source/sink needs confluent-kafka. Install the extra:\n pip install 'logreducer[kafka]'"
|
|
@@ -75,20 +74,35 @@ _INSTALL_HINT = (
|
|
|
75
74
|
def merge_config(user_config: dict[str, Any], defaults: dict[str, Any], verify_ssl: bool = True) -> dict[str, Any]:
|
|
76
75
|
"""Overlay ``user_config`` on ``defaults``; optionally disable TLS verify.
|
|
77
76
|
|
|
78
|
-
User values win over defaults.
|
|
77
|
+
User values win over defaults. Verification turned off, by ``verify_ssl`` or by the
|
|
78
|
+
config, warns once per process.
|
|
79
79
|
"""
|
|
80
|
+
global _warned_unverified
|
|
80
81
|
merged = {**defaults, **user_config}
|
|
81
82
|
if not verify_ssl:
|
|
82
83
|
merged["enable.ssl.certificate.verification"] = "false"
|
|
84
|
+
verification = str(merged.get("enable.ssl.certificate.verification", "true")).strip().lower()
|
|
85
|
+
if verification in ("false", "0") and not _warned_unverified:
|
|
86
|
+
_warned_unverified = True
|
|
87
|
+
warnings.warn(
|
|
88
|
+
"Kafka TLS certificate verification is off, so the broker's identity is not checked",
|
|
89
|
+
RuntimeWarning,
|
|
90
|
+
stacklevel=3,
|
|
91
|
+
)
|
|
83
92
|
return merged
|
|
84
93
|
|
|
85
94
|
|
|
95
|
+
def _is_credential(key: str) -> bool:
|
|
96
|
+
key = key.lower()
|
|
97
|
+
return key in _CREDENTIAL_KEYS or key.endswith(_CREDENTIAL_SUFFIXES) or any(p in key for p in _CREDENTIAL_PARTS)
|
|
98
|
+
|
|
99
|
+
|
|
86
100
|
def mask_credentials(config: dict[str, Any]) -> dict[str, Any]:
|
|
87
101
|
"""Return a copy of ``config`` with credential values replaced by ``***``.
|
|
88
102
|
|
|
89
103
|
Used in ``__repr__`` so a Kafka config never leaks secrets into logs.
|
|
90
104
|
"""
|
|
91
|
-
return {k: ("***" if k
|
|
105
|
+
return {k: ("***" if _is_credential(k) and v not in (None, "") else v) for k, v in config.items()}
|
|
92
106
|
|
|
93
107
|
|
|
94
108
|
class KafkaConsumerError(Exception):
|
|
@@ -54,7 +54,7 @@ _DISABLED_LEVEL = logging.CRITICAL + 1
|
|
|
54
54
|
_FILE_MAX_BYTES = 10 * 1024 * 1024
|
|
55
55
|
_FILE_BACKUPS = 7
|
|
56
56
|
|
|
57
|
-
# Every attribute a bare LogRecord carries
|
|
57
|
+
# Every attribute a bare LogRecord carries. Anything else came from the caller's ``extra=``.
|
|
58
58
|
_STANDARD_RECORD_ATTRS = frozenset(logging.LogRecord("", 0, "", 0, "", (), None).__dict__) | {"message", "asctime"}
|
|
59
59
|
|
|
60
60
|
# Handlers this module has attached, so re-configuring only tears down our own
|
|
@@ -180,7 +180,8 @@ def setup_logging(
|
|
|
180
180
|
at the host's level. This is the embedding seam: a host app that owns
|
|
181
181
|
logging calls ``setup_logging(enable=True, own_sinks=False)`` and
|
|
182
182
|
logreducer's output lands in the host's sinks, formatted by the
|
|
183
|
-
host's standard.
|
|
183
|
+
host's standard. Building a ``LogReducer`` applies its config's
|
|
184
|
+
logging, so call this after the reducer is built.
|
|
184
185
|
|
|
185
186
|
Raises:
|
|
186
187
|
ValueError: If the resolved level is not a ``logging`` level name.
|
|
@@ -136,7 +136,7 @@ class StreamingProcessor:
|
|
|
136
136
|
|
|
137
137
|
The memory check runs on its own line counter, NOT on chunk-flush
|
|
138
138
|
boundaries - a flush count and a line count almost never coincide, so
|
|
139
|
-
gating the check on both
|
|
139
|
+
gating the check on both would make this fallback dead.
|
|
140
140
|
"""
|
|
141
141
|
chunk: list[str] = []
|
|
142
142
|
check_every = 100_000
|
|
@@ -112,21 +112,32 @@ class SevereShapes:
|
|
|
112
112
|
Numbers, IPs, hex runs and ISO-8601 timestamps do not change a shape, and digits inside an
|
|
113
113
|
identifier do (``E1`` and ``E2`` are two shapes). The reducer feeds it every line as the
|
|
114
114
|
source is read, before any sampling or dedup, so a severe line cannot be lost to either.
|
|
115
|
-
It holds one line per distinct shape.
|
|
115
|
+
It holds one line per distinct shape, up to ``cap`` shapes.
|
|
116
|
+
|
|
117
|
+
Attributes:
|
|
118
|
+
cap: Shapes kept, the first to appear. ``None`` keeps every shape.
|
|
119
|
+
dropped: Severe lines of a new shape that arrived once ``cap`` shapes were kept.
|
|
116
120
|
"""
|
|
117
121
|
|
|
118
|
-
def __init__(self) -> None:
|
|
122
|
+
def __init__(self, cap: int | None = None) -> None:
|
|
123
|
+
self.cap = cap
|
|
124
|
+
self.dropped = 0
|
|
119
125
|
self._masks = _typed_masking_instructions(timestamp=True)
|
|
120
126
|
self._first_of_shape: dict[str, str] = {}
|
|
121
127
|
|
|
122
128
|
def add(self, line: str) -> None:
|
|
123
|
-
"""Remember ``line`` when it is severe and its shape is new
|
|
129
|
+
"""Remember ``line`` when it is severe and its shape is new, while under ``cap``."""
|
|
124
130
|
if not is_severe(line):
|
|
125
131
|
return
|
|
126
132
|
shape = line
|
|
127
133
|
for mask in self._masks:
|
|
128
134
|
shape = mask.mask(shape)
|
|
129
|
-
self._first_of_shape
|
|
135
|
+
if shape in self._first_of_shape:
|
|
136
|
+
return
|
|
137
|
+
if self.cap is not None and len(self._first_of_shape) >= self.cap:
|
|
138
|
+
self.dropped += 1
|
|
139
|
+
return
|
|
140
|
+
self._first_of_shape[shape] = line
|
|
130
141
|
|
|
131
142
|
@property
|
|
132
143
|
def lines(self) -> list[str]:
|
|
@@ -246,6 +257,7 @@ class PatternExtractor:
|
|
|
246
257
|
# Bound the template store when configured: the miner LRU-evicts beyond
|
|
247
258
|
# drain_max_clusters, keeping memory flat on high-cardinality logs.
|
|
248
259
|
drain_max_clusters=self.config.max_clusters,
|
|
260
|
+
drain_max_leaf_clusters=self.config.max_leaf_clusters,
|
|
249
261
|
masking_instructions=masking,
|
|
250
262
|
drain_is_severe=is_severe,
|
|
251
263
|
)
|
|
@@ -62,10 +62,15 @@ class FileSource:
|
|
|
62
62
|
Attributes:
|
|
63
63
|
severe_shapes: One severe line per shape, from every line the latest pass read,
|
|
64
64
|
including the ones that pass sampled away.
|
|
65
|
+
max_severe_shapes: Shapes ``severe_shapes`` keeps. ``None`` keeps every shape.
|
|
66
|
+
``LogReducer.reduce`` lowers it to the reducer's own cap.
|
|
65
67
|
"""
|
|
66
68
|
|
|
67
|
-
def __init__(
|
|
69
|
+
def __init__(
|
|
70
|
+
self, path: str | os.PathLike[str], *, max_memory_gb: float = 1.0, max_severe_shapes: int | None = None
|
|
71
|
+
) -> None:
|
|
68
72
|
self.path = os.fspath(path)
|
|
73
|
+
self.max_severe_shapes = max_severe_shapes
|
|
69
74
|
# A pipe or device can be read once, but reduce() reads a source more than
|
|
70
75
|
# once, so the second pass would see nothing and return an empty result.
|
|
71
76
|
if os.path.exists(self.path) and not os.path.isfile(self.path):
|
|
@@ -74,11 +79,11 @@ class FileSource:
|
|
|
74
79
|
"so write it to a file first (e.g. redirect into a temp file)."
|
|
75
80
|
)
|
|
76
81
|
self._processor = StreamingProcessor(MemoryMonitor(max_memory_gb))
|
|
77
|
-
self.severe_shapes = SevereShapes()
|
|
82
|
+
self.severe_shapes = SevereShapes(max_severe_shapes)
|
|
78
83
|
|
|
79
84
|
def __iter__(self) -> Iterator[str]:
|
|
80
85
|
# A fresh tap per pass: it sees every line of the file, however the pass samples.
|
|
81
|
-
self.severe_shapes = SevereShapes()
|
|
86
|
+
self.severe_shapes = SevereShapes(self.max_severe_shapes)
|
|
82
87
|
return self._processor.read_file_streaming(self.path, self.severe_shapes.add)
|
|
83
88
|
|
|
84
89
|
@property
|
|
@@ -41,7 +41,7 @@ Derived from Drain3 at commit 0fb6d6e1828838fa05c8f6fa5cda878e02ea79c7. It keeps
|
|
|
41
41
|
only the streaming path logreducer drives: mask a line, route it through a
|
|
42
42
|
fixed-depth prefix tree, and merge it into the most similar cluster of the same
|
|
43
43
|
token count, widening differing tokens to ``<*>``. Drain3's copyright and MIT
|
|
44
|
-
licence notice are in the header above
|
|
44
|
+
licence notice are in the header above, and the README credits Drain3 and logparser.
|
|
45
45
|
"""
|
|
46
46
|
|
|
47
47
|
import re
|
|
@@ -49,7 +49,7 @@ from collections import OrderedDict
|
|
|
49
49
|
from collections.abc import Callable, Iterable, Sequence
|
|
50
50
|
from dataclasses import dataclass
|
|
51
51
|
|
|
52
|
-
# Wildcard a widened template slot carries
|
|
52
|
+
# Wildcard a widened template slot carries. Masks render as <NAME> in the same shape.
|
|
53
53
|
_PARAM_STR = "<*>"
|
|
54
54
|
|
|
55
55
|
|
|
@@ -62,15 +62,17 @@ class LogCluster:
|
|
|
62
62
|
size: Lines merged into this cluster.
|
|
63
63
|
severe: Whether the line that founded the cluster was severe, as judged by
|
|
64
64
|
the miner's ``is_severe`` predicate. Every merged line shares it.
|
|
65
|
+
last_used: The miner's line number when the cluster last took a line.
|
|
65
66
|
"""
|
|
66
67
|
|
|
67
|
-
__slots__ = ("cluster_id", "log_template_tokens", "severe", "size")
|
|
68
|
+
__slots__ = ("cluster_id", "last_used", "log_template_tokens", "severe", "size")
|
|
68
69
|
|
|
69
70
|
def __init__(self, log_template_tokens: Iterable[str], cluster_id: int, severe: bool = False) -> None:
|
|
70
71
|
self.log_template_tokens = tuple(log_template_tokens)
|
|
71
72
|
self.cluster_id = cluster_id
|
|
72
73
|
self.size = 1
|
|
73
74
|
self.severe = severe
|
|
75
|
+
self.last_used = 0
|
|
74
76
|
|
|
75
77
|
def get_template(self) -> str:
|
|
76
78
|
"""Return the template as one space-joined string."""
|
|
@@ -80,7 +82,7 @@ class LogCluster:
|
|
|
80
82
|
class ClusterStore:
|
|
81
83
|
"""Cluster id to cluster map, optionally bounded by least-recently-used eviction.
|
|
82
84
|
|
|
83
|
-
Storing and ``touch`` mark a cluster as used
|
|
85
|
+
Storing and ``touch`` mark a cluster as used. ``get`` and ``in`` only look, so
|
|
84
86
|
scoring candidate clusters never changes which one is evicted next.
|
|
85
87
|
"""
|
|
86
88
|
|
|
@@ -152,6 +154,8 @@ class Drain:
|
|
|
152
154
|
max_node_depth: Depth of the leaf nodes, counting the token-count level as 1.
|
|
153
155
|
sim_th: Minimum share of matching tokens to join an existing cluster.
|
|
154
156
|
max_children: Children a tree node holds before new tokens share ``<*>``.
|
|
157
|
+
max_leaf_clusters: Clusters a leaf offers a line, the most recently used
|
|
158
|
+
kept. ``None`` offers every live cluster, which is Drain3's behaviour.
|
|
155
159
|
is_severe: Predicate that marks a line as severe. A severe line never
|
|
156
160
|
joins a non-severe cluster, and the reverse, so a level word is never
|
|
157
161
|
widened to ``<*>`` by a non-severe neighbour. ``None`` treats every
|
|
@@ -159,6 +163,10 @@ class Drain:
|
|
|
159
163
|
root_node: Root of the prefix tree.
|
|
160
164
|
id_to_cluster: Every live cluster, keyed by id.
|
|
161
165
|
clusters_counter: The id given to the newest cluster.
|
|
166
|
+
|
|
167
|
+
One-token lines all reach the same leaf, and with ``sim_th`` above 0 they can
|
|
168
|
+
only join the cluster holding the same token, so they are looked up by token
|
|
169
|
+
instead of scored against every cluster at that leaf.
|
|
162
170
|
"""
|
|
163
171
|
|
|
164
172
|
def __init__(
|
|
@@ -168,6 +176,7 @@ class Drain:
|
|
|
168
176
|
max_children: int = 100,
|
|
169
177
|
max_clusters: int | None = None,
|
|
170
178
|
is_severe: Callable[[str], bool] | None = None,
|
|
179
|
+
max_leaf_clusters: int | None = None,
|
|
171
180
|
) -> None:
|
|
172
181
|
"""Create an empty miner.
|
|
173
182
|
|
|
@@ -180,19 +189,34 @@ class Drain:
|
|
|
180
189
|
``None`` keeps every cluster.
|
|
181
190
|
is_severe: Predicate that keeps severe and non-severe lines in
|
|
182
191
|
separate clusters. ``None`` treats every line alike.
|
|
192
|
+
max_leaf_clusters: Clusters a leaf offers a line, which bounds the
|
|
193
|
+
comparisons per line. Past it the leaf drops its least recently
|
|
194
|
+
used cluster, which stays live but takes no more lines. ``None``
|
|
195
|
+
offers every live cluster.
|
|
183
196
|
|
|
184
197
|
Raises:
|
|
185
|
-
ValueError: If ``depth`` is below 3 or ``max_clusters``
|
|
198
|
+
ValueError: If ``depth`` is below 3, or ``max_clusters`` or
|
|
199
|
+
``max_leaf_clusters`` is below 1.
|
|
186
200
|
"""
|
|
187
201
|
if depth < 3:
|
|
188
202
|
raise ValueError(f"depth must be at least 3, not {depth}")
|
|
203
|
+
if max_leaf_clusters is not None and max_leaf_clusters < 1:
|
|
204
|
+
raise ValueError(f"max_leaf_clusters must be at least 1, not {max_leaf_clusters}")
|
|
189
205
|
self.max_node_depth = depth - 2
|
|
190
206
|
self.sim_th = sim_th
|
|
191
207
|
self.max_children = max_children
|
|
208
|
+
self.max_leaf_clusters = max_leaf_clusters
|
|
192
209
|
self.is_severe = is_severe
|
|
193
210
|
self.root_node = Node()
|
|
194
211
|
self.id_to_cluster = ClusterStore(max_clusters)
|
|
195
212
|
self.clusters_counter = 0
|
|
213
|
+
self._lines_seen = 0
|
|
214
|
+
# (token, severe) to cluster id for one-token clusters, which may name evicted ids.
|
|
215
|
+
self._one_token_ids: dict[tuple[str, bool], int] = {}
|
|
216
|
+
|
|
217
|
+
def _indexes_one_token(self, token: str) -> bool:
|
|
218
|
+
"""True when a one-token line can only join the cluster holding the same token."""
|
|
219
|
+
return 0 < self.sim_th <= 1 and token != _PARAM_STR
|
|
196
220
|
|
|
197
221
|
@property
|
|
198
222
|
def clusters(self) -> list[LogCluster]:
|
|
@@ -211,16 +235,19 @@ class Drain:
|
|
|
211
235
|
content_tokens = content.split()
|
|
212
236
|
severe = self.is_severe is not None and self.is_severe(content)
|
|
213
237
|
match_cluster = self.tree_search(content_tokens, severe)
|
|
238
|
+
self._lines_seen += 1
|
|
214
239
|
|
|
215
240
|
if match_cluster is None:
|
|
216
241
|
self.clusters_counter += 1
|
|
217
242
|
match_cluster = LogCluster(content_tokens, self.clusters_counter, severe)
|
|
243
|
+
match_cluster.last_used = self._lines_seen
|
|
218
244
|
self.id_to_cluster[match_cluster.cluster_id] = match_cluster
|
|
219
245
|
self.add_seq_to_prefix_tree(match_cluster)
|
|
220
246
|
return match_cluster
|
|
221
247
|
|
|
222
248
|
match_cluster.log_template_tokens = self.create_template(content_tokens, match_cluster.log_template_tokens)
|
|
223
249
|
match_cluster.size += 1
|
|
250
|
+
match_cluster.last_used = self._lines_seen
|
|
224
251
|
self.id_to_cluster.touch(match_cluster.cluster_id)
|
|
225
252
|
return match_cluster
|
|
226
253
|
|
|
@@ -243,6 +270,10 @@ class Drain:
|
|
|
243
270
|
if token_count == 0:
|
|
244
271
|
return self.id_to_cluster.get(cur_node.cluster_ids[0])
|
|
245
272
|
|
|
273
|
+
if token_count == 1 and self._indexes_one_token(tokens[0]):
|
|
274
|
+
cluster_id = self._one_token_ids.get((tokens[0], severe))
|
|
275
|
+
return None if cluster_id is None else self.id_to_cluster.get(cluster_id)
|
|
276
|
+
|
|
246
277
|
cur_node_depth = 1
|
|
247
278
|
for token in tokens:
|
|
248
279
|
if cur_node_depth >= self.max_node_depth or cur_node_depth == token_count:
|
|
@@ -273,13 +304,31 @@ class Drain:
|
|
|
273
304
|
cur_node.cluster_ids = [cluster.cluster_id]
|
|
274
305
|
return
|
|
275
306
|
|
|
307
|
+
if token_count == 1 and self._indexes_one_token(cluster.log_template_tokens[0]):
|
|
308
|
+
self._one_token_ids[(cluster.log_template_tokens[0], cluster.severe)] = cluster.cluster_id
|
|
309
|
+
# Dropping evicted ids at twice the live count costs O(1) per line, amortised.
|
|
310
|
+
if len(self._one_token_ids) >= 2 * len(self.id_to_cluster):
|
|
311
|
+
self._one_token_ids = {
|
|
312
|
+
key: cluster_id
|
|
313
|
+
for key, cluster_id in self._one_token_ids.items()
|
|
314
|
+
if cluster_id in self.id_to_cluster
|
|
315
|
+
}
|
|
316
|
+
return
|
|
317
|
+
|
|
276
318
|
current_depth = 1
|
|
277
319
|
for token in cluster.log_template_tokens:
|
|
278
320
|
if current_depth >= self.max_node_depth or current_depth >= token_count:
|
|
279
321
|
# Drop ids the store has evicted before adding the new one.
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
322
|
+
live: list[LogCluster] = []
|
|
323
|
+
for cluster_id in cur_node.cluster_ids:
|
|
324
|
+
kept = self.id_to_cluster.get(cluster_id)
|
|
325
|
+
if kept is not None:
|
|
326
|
+
live.append(kept)
|
|
327
|
+
if self.max_leaf_clusters is not None and len(live) >= self.max_leaf_clusters:
|
|
328
|
+
# Removed in place, because list order breaks ties in fast_match.
|
|
329
|
+
live.remove(min(live, key=lambda candidate: candidate.last_used))
|
|
330
|
+
cur_node.cluster_ids = [kept.cluster_id for kept in live]
|
|
331
|
+
cur_node.cluster_ids.append(cluster.cluster_id)
|
|
283
332
|
break
|
|
284
333
|
|
|
285
334
|
children = cur_node.key_to_child_node
|
|
@@ -416,6 +465,8 @@ class TemplateMinerConfig:
|
|
|
416
465
|
drain_max_children: Children a tree node holds before new tokens share ``<*>``.
|
|
417
466
|
drain_max_clusters: Clusters kept before the least recently used is evicted.
|
|
418
467
|
``None`` keeps every cluster.
|
|
468
|
+
drain_max_leaf_clusters: Clusters a leaf offers a line (see :class:`Drain`).
|
|
469
|
+
``None`` offers every live cluster.
|
|
419
470
|
masking_instructions: Masks applied to each line in order, before clustering.
|
|
420
471
|
drain_is_severe: Predicate that keeps severe and non-severe lines in
|
|
421
472
|
separate clusters (see :class:`Drain`). ``None`` treats every line alike.
|
|
@@ -425,6 +476,7 @@ class TemplateMinerConfig:
|
|
|
425
476
|
drain_depth: int = 4
|
|
426
477
|
drain_max_children: int = 100
|
|
427
478
|
drain_max_clusters: int | None = None
|
|
479
|
+
drain_max_leaf_clusters: int | None = None
|
|
428
480
|
masking_instructions: tuple[MaskingInstruction, ...] = ()
|
|
429
481
|
drain_is_severe: Callable[[str], bool] | None = None
|
|
430
482
|
|
|
@@ -441,7 +493,7 @@ class TemplateMiner:
|
|
|
441
493
|
"""Create an empty miner.
|
|
442
494
|
|
|
443
495
|
Args:
|
|
444
|
-
config: Tuning
|
|
496
|
+
config: Tuning. ``None`` uses the :class:`TemplateMinerConfig` defaults.
|
|
445
497
|
"""
|
|
446
498
|
self.config = config if config is not None else TemplateMinerConfig()
|
|
447
499
|
self.drain = Drain(
|
|
@@ -450,6 +502,7 @@ class TemplateMiner:
|
|
|
450
502
|
max_children=self.config.drain_max_children,
|
|
451
503
|
max_clusters=self.config.drain_max_clusters,
|
|
452
504
|
is_severe=self.config.drain_is_severe,
|
|
505
|
+
max_leaf_clusters=self.config.drain_max_leaf_clusters,
|
|
453
506
|
)
|
|
454
507
|
|
|
455
508
|
def add_log_message(self, log_message: str) -> LogCluster:
|
|
@@ -6,7 +6,7 @@ from dataclasses import dataclass
|
|
|
6
6
|
from datetime import UTC, datetime
|
|
7
7
|
from typing import Any
|
|
8
8
|
|
|
9
|
-
from .template_mining import TemplateMiner
|
|
9
|
+
from .template_mining import TemplateMiner, TemplateMinerConfig
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
@dataclass
|
|
@@ -74,14 +74,21 @@ class TimestampParser:
|
|
|
74
74
|
|
|
75
75
|
|
|
76
76
|
class TemporalProcessor:
|
|
77
|
-
"""Time-aware log processing.
|
|
77
|
+
"""Time-aware log processing.
|
|
78
78
|
|
|
79
|
-
|
|
79
|
+
Each time window, and the lines with no timestamp, get a template miner bounded
|
|
80
|
+
by ``max_clusters`` and ``max_leaf_clusters`` (see :class:`~logreducer.template_mining.Drain`).
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
def __init__(self, window_minutes: int = 60, max_clusters: int | None = None, max_leaf_clusters: int | None = None):
|
|
80
84
|
if window_minutes < 1:
|
|
81
85
|
raise ValueError(f"window_minutes must be at least 1, got {window_minutes!r}")
|
|
82
86
|
self.window_minutes = window_minutes
|
|
83
87
|
self.parser = TimestampParser()
|
|
84
88
|
self.miners_by_window: dict[int, TemplateMiner] = {}
|
|
89
|
+
self._miner_config = TemplateMinerConfig(
|
|
90
|
+
drain_max_clusters=max_clusters, drain_max_leaf_clusters=max_leaf_clusters
|
|
91
|
+
)
|
|
85
92
|
|
|
86
93
|
def process_temporal(self, lines: list[str]) -> dict:
|
|
87
94
|
"""Process with temporal awareness."""
|
|
@@ -122,7 +129,7 @@ class TemporalProcessor:
|
|
|
122
129
|
# One pattern per template within each window.
|
|
123
130
|
for window_key, window_entries in windows.items():
|
|
124
131
|
if window_key not in self.miners_by_window:
|
|
125
|
-
self.miners_by_window[window_key] = TemplateMiner()
|
|
132
|
+
self.miners_by_window[window_key] = TemplateMiner(self._miner_config)
|
|
126
133
|
|
|
127
134
|
for pattern in self._summarise(self.miners_by_window[window_key], window_entries):
|
|
128
135
|
patterns.append({**pattern, "window": window_key})
|
|
@@ -131,7 +138,7 @@ class TemporalProcessor:
|
|
|
131
138
|
|
|
132
139
|
def _extract_timeless_patterns(self, entries: list[LogEntry]) -> list[dict]:
|
|
133
140
|
"""Extract patterns without timestamps."""
|
|
134
|
-
return self._summarise(TemplateMiner(), entries)
|
|
141
|
+
return self._summarise(TemplateMiner(self._miner_config), entries)
|
|
135
142
|
|
|
136
143
|
@staticmethod
|
|
137
144
|
def _summarise(miner: TemplateMiner, entries: list[LogEntry]) -> list[dict]:
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|