From 8a51649a6789eb7e4e31b3d8ed9bad7347eca312 Mon Sep 17 00:00:00 2001 From: Ajimaru Date: Sun, 5 Jul 2026 23:06:22 +0200 Subject: [PATCH 1/2] feat: log parsing, i18n catalog sync, and rotation test fixes (v0.2.4) Squashed dev onto main to linearize history and drop a duplicate actions/checkout bump that made the PR un-rebasable on GitHub. main already contained no commits absent from dev, so no main-side work is lost. Includes: - log_parser module and tests - regenerated messages.pot / German catalog (no stray build/lib paths) - copy-truncate rotation test split to remove a 3.12 thread race - ruff per-file-ignore for tests, codespell typo fix Co-Authored-By: Claude Opus 4.8 --- .github/workflows/bandit-sarif.yml | 2 +- .github/workflows/ci.yml | 4 +- .github/workflows/codeql.yml | 2 +- .github/workflows/docs.yml | 2 +- .github/workflows/i18n.yml | 2 +- .github/workflows/lint.yml | 2 +- .github/workflows/release.yml | 4 +- .github/workflows/vibe-coded.yml | 2 +- CHANGELOG.md | 45 +++- README.md | 28 ++- docs/api/python.md | 4 + docs/changelog.md | 3 +- docs/configuration.md | 59 +++++ docs/index.md | 13 +- docs/overview.md | 46 +++- docs/rest-api.md | 156 ++++++++++++ docs/troubleshooting.md | 47 ++++ mkdocs.yml | 3 + octoprint_logmonitor/__init__.py | 234 +++++++++++------- octoprint_logmonitor/_version.py | 2 +- octoprint_logmonitor/log_parser.py | 138 +++++++++++ octoprint_logmonitor/log_searcher.py | 188 ++++++-------- octoprint_logmonitor/log_tailer.py | 159 ++++-------- octoprint_logmonitor/security.py | 28 ++- octoprint_logmonitor/static/js/logmonitor.js | 42 +--- .../templates/logmonitor_settings.jinja2 | 2 +- .../translations/de/LC_MESSAGES/messages.mo | Bin 7737 -> 8204 bytes pyproject.toml | 5 +- tests/test_log_parser.py | 90 +++++++ tests/test_log_tailer.py | 90 ++++++- tests/test_plugin_core.py | 35 ++- translations/de/LC_MESSAGES/messages.mo | Bin 7737 -> 8156 bytes translations/de/LC_MESSAGES/messages.po | 36 +-- translations/messages.pot | 26 +- 34 files changed, 1080 insertions(+), 419 deletions(-) create mode 100644 docs/configuration.md create mode 100644 docs/rest-api.md create mode 100644 docs/troubleshooting.md create mode 100644 octoprint_logmonitor/log_parser.py create mode 100644 tests/test_log_parser.py diff --git a/.github/workflows/bandit-sarif.yml b/.github/workflows/bandit-sarif.yml index e2fdf8e..a826515 100644 --- a/.github/workflows/bandit-sarif.yml +++ b/.github/workflows/bandit-sarif.yml @@ -26,7 +26,7 @@ jobs: steps: - # Checkout repository code name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 - # Setup Python for Bandit scanning name: Set up Python diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5b55b93..dfd8e46 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -53,7 +53,7 @@ jobs: steps: - # Checkout repository code name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 - # Setup Python version and pip cache name: Set up Python @@ -191,7 +191,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 - name: Set up Python uses: actions/setup-python@v6 diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index dafcf27..9e46925 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -59,7 +59,7 @@ jobs: # your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 # Add any setup steps before running the `github/codeql-action/init` action. # This includes steps like installing compilers or runtimes (`actions/setup-node` diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 4043bd9..3c17ad8 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -24,7 +24,7 @@ jobs: steps: - # Checkout repository code name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 - # Setup Python for MkDocs build name: Set up Python diff --git a/.github/workflows/i18n.yml b/.github/workflows/i18n.yml index dc5e73e..d6e28ce 100644 --- a/.github/workflows/i18n.yml +++ b/.github/workflows/i18n.yml @@ -21,7 +21,7 @@ jobs: steps: - # Checkout repository code name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 - # Setup Python 3.12 for i18n tools name: Set up Python diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 0e5be5b..c5dbf22 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -26,7 +26,7 @@ jobs: steps: - # Checkout repository code name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 - # Setup Python and pip cache name: Set up Python diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 726f4b6..5acc737 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,7 +15,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 - name: Set up Python uses: actions/setup-python@v6 @@ -146,7 +146,7 @@ jobs: echo "title=$title" >> "$GITHUB_OUTPUT" - name: Create GitHub Release - uses: softprops/action-gh-release@b4309332981a82ec1c5618f44dd2e27cc8bfbfda # v3 + uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3 with: name: ${{ steps.release_title.outputs.title }} draft: false diff --git a/.github/workflows/vibe-coded.yml b/.github/workflows/vibe-coded.yml index 127df0e..131967c 100644 --- a/.github/workflows/vibe-coded.yml +++ b/.github/workflows/vibe-coded.yml @@ -28,7 +28,7 @@ jobs: # rejected by the protected branch. Falls back to GITHUB_TOKEN if the # secret is unset (push will then be skipped, not fail the run). name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: fetch-depth: 0 token: ${{ secrets.VIBE_BADGE_TOKEN || secrets.GITHUB_TOKEN }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 1be89fd..19073a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,46 @@ # Changelog -See the releases on GitHub for detailed changelogs once you publish this plugin: [https://github.com/Ajimaru/OctoPrint-LogMonitor/releases](https://github.com/Ajimaru/OctoPrint-LogMonitor/releases) +All notable changes to this project are documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +For the detailed history of published versions, see the +[GitHub releases](https://github.com/Ajimaru/OctoPrint-LogMonitor/releases). + +## [Unreleased] + +### Added + +- Shared `log_parser` module: streaming and searching now classify log + lines identically (search understands serial and compact formats too). +- Copy-truncate log rotation detection: a truncated file no longer stalls + the live stream. +- Documentation: configuration reference, REST API reference, and + troubleshooting guide. + +### Changed + +- Search now streams through log files line by line instead of loading + them fully into memory; the initial-lines read also uses backward block + reads. Memory use no longer scales with file size. +- Hyphenated logger names (e.g. `octoprint.plugins.my-plugin`) parse + correctly. +- `max_alert_history` is now consistently capped at 500 in settings, UI, + and runtime. + +### Fixed + +- Batched line delivery now starts reliably for auto-started and + multi-file streams, and stopping the single-file stream no longer stalls + active multi-file streams. +- The line buffer is hard-capped so memory stays bounded even if flushing + stalls; the search rate limiter prunes idle clients automatically. +- `POST /stream/multi/stop` with `stop_all` reports the actual number of + stopped streams. + +## [0.2.3] - 2026-06 + +- Version 0.2.3: improved log path validation and error handling. + +See [GitHub releases](https://github.com/Ajimaru/OctoPrint-LogMonitor/releases) +for earlier versions. diff --git a/README.md b/README.md index cc74e12..9855263 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,14 @@ - 🔀 **Multi-Stream API** - Backend endpoints for parallel streaming of multiple logs - 🛡️ **Secure** - Path traversal protection, input validation, and rate limiting +## Documentation + +Full documentation lives at **[ajimaru.github.io/OctoPrint-LogMonitor](https://ajimaru.github.io/OctoPrint-LogMonitor/)**: + +- [Configuration reference](https://ajimaru.github.io/OctoPrint-LogMonitor/configuration/) - every setting, default, and limit +- [REST API reference](https://ajimaru.github.io/OctoPrint-LogMonitor/rest-api/) - all plugin endpoints and WebSocket push messages +- [Troubleshooting](https://ajimaru.github.io/OctoPrint-LogMonitor/troubleshooting/) - common problems and fixes + ## Installation ### Via Plugin Manager (Recommended) @@ -70,7 +78,7 @@ The `releases/latest` URL always points to the newest stable release. ## Configuration -Access plugin settings via OctoPrint Settings → Plugins → Log Monitor +Access plugin settings via OctoPrint Settings → Plugins → Log Monitor. The most important options are listed below; see the [configuration reference](https://ajimaru.github.io/OctoPrint-LogMonitor/configuration/) for the complete list with ranges and built-in limits. ### Display Settings @@ -131,6 +139,24 @@ When a log entry matches configured trigger severities (default: WARNING/ERROR/C - The Sidebar widget updates (if enabled) - Click the badge/widget to open the Log Monitor tab and reset alerts +## Development + +```bash +git clone https://github.com/Ajimaru/OctoPrint-LogMonitor.git +cd OctoPrint-LogMonitor +python -m venv .venv && source .venv/bin/activate +python -m pip install -e .[develop] + +# Run the test suite +python -m pytest + +# Lint / format +python -m flake8 octoprint_logmonitor tests +python -m black octoprint_logmonitor tests +``` + +The plugin API used by the frontend is documented in the [REST API reference](https://ajimaru.github.io/OctoPrint-LogMonitor/rest-api/). + ## Contributing Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines and instructions. diff --git a/docs/api/python.md b/docs/api/python.md index 489a27e..7c31943 100644 --- a/docs/api/python.md +++ b/docs/api/python.md @@ -2,6 +2,10 @@ This page is generated from Python docstrings. +## `log_parser` + +::: octoprint_logmonitor.log_parser + ## `log_searcher` ::: octoprint_logmonitor.log_searcher diff --git a/docs/changelog.md b/docs/changelog.md index 7e58d0f..cadc6ac 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -3,7 +3,8 @@ Use the GitHub releases page for the detailed history of published versions. - [Releases](https://github.com/Ajimaru/OctoPrint-LogMonitor/releases) +- [`CHANGELOG.md`](https://github.com/Ajimaru/OctoPrint-LogMonitor/blob/main/CHANGELOG.md) — unreleased changes ## Current release line -- 0.1.x: initial public plugin line with log streaming, search, alerts, and security controls +- 0.2.x: log streaming, search, alerts, multi-file streaming API, and security controls diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..dbc23d3 --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,59 @@ +# Configuration Reference + +All settings live under **OctoPrint Settings → Plugins → Log Monitor**. +Values outside the allowed range are clamped automatically when saved. + +## Display + +| Setting | Default | Description | +| -------------- | ------- | ------------------------------------------------ | +| `show_navbar` | `true` | Show the alert badge in the OctoPrint navbar. | +| `show_sidebar` | `true` | Show the status widget in the OctoPrint sidebar. | + +## Streaming + +| Setting | Default | Range | Description | +| ------------------------ | --------------- | --------- | --------------------------------------------------------------------------- | +| `default_log_file` | `octoprint.log` | — | Log file preselected in the tab and used for auto-start. | +| `stream_poll_interval_s` | `5` | 1–60 s | How often the tailer polls for new lines and batches are flushed to the UI. | +| `max_stream_lines` | `500` | 100–10000 | Maximum lines kept in the live view buffer. | +| `auto_scroll` | `true` | — | Scroll to the newest line automatically. | +| `auto_start_streaming` | `false` | — | Start streaming `default_log_file` when OctoPrint starts. | + +## Search + +| Setting | Default | Range | Description | +| ---------------------- | ------- | ------ | -------------------------------------------------- | +| `search_page_size` | `50` | 10–500 | Results per page. | +| `regex_search_enabled` | `false` | — | Allow regular-expression queries in the search UI. | + +## Alerts + +| Setting | Default | Range | Description | +| ----------------------- | -------------------------------- | ------ | -------------------------------------------------------------------------- | +| `alerts_enabled` | `true` | — | Master switch for severity alerting. | +| `severity_triggers` | `["WARNING","ERROR","CRITICAL"]` | — | Levels that raise an alert. | +| `alerts_monitor_mode` | `selected` | — | `all` monitors every `.log` file; `selected` only `alerts_monitored_logs`. | +| `alerts_monitored_logs` | `["octoprint.log"]` | — | Files watched by the background alert monitor (mode `selected`). | +| `alert_history_enabled` | `true` | — | Keep a history of triggered alerts. | +| `max_alert_history` | `100` | 10–500 | Maximum stored history entries. | +| `enable_notifications` | `false` | — | Show a toast notification for each alert. | + +The alert monitor runs independently of the live-stream view: alerts are +raised even while the Log Monitor tab is closed. + +## Privacy & Debugging + +| Setting | Default | Description | +| ------------------ | ------- | ------------------------------------------------------------------------------------------------------- | +| `mask_log_content` | `false` | Mask API keys, passwords, tokens, and e-mail addresses in streamed lines before they reach the browser. | +| `debug_mode` | `false` | Enable verbose plugin logging and the debug endpoints (frontend event log, test entries). | + +## Built-in limits + +These are hard limits enforced by the backend regardless of settings: + +- Log files larger than **1 GiB** are rejected for search and streaming. +- Search requests are rate limited to **10 per minute per client**. +- At most **20 files** per multi-stream request. +- Search `limit` parameter caps at **1000**; alert-history `limit` at **500**. diff --git a/docs/index.md b/docs/index.md index 3306f82..b07ecd8 100644 --- a/docs/index.md +++ b/docs/index.md @@ -7,11 +7,18 @@ Live log streaming and search for OctoPrint, with severity alerts in the navbar - Real-time log streaming - Full-text search with pagination and severity filters - Navbar and sidebar alert badges -- Log download and alert history +- Log download, search-result export, and alert history -## Links +## Documentation + +- [Plugin Overview](overview.md) — features and architecture +- [Configuration Reference](configuration.md) — every setting, default, and limit +- [REST API Reference](rest-api.md) — all plugin endpoints and push messages +- [Troubleshooting](troubleshooting.md) — common problems and fixes +- [Python API](api/python.md) — generated from docstrings + +## Project -- [Plugin Overview](overview.md) - [Contributing](contributing.md) - [Security](security.md) - [Changelog](changelog.md) diff --git a/docs/overview.md b/docs/overview.md index f8a0b37..1446999 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -1,15 +1,45 @@ # Plugin Overview -OctoPrint Log Monitor streams OctoPrint logs, searches them with pagination and severity filters, and shows alert badges in the navbar and sidebar. +OctoPrint Log Monitor streams OctoPrint logs live, searches them with +pagination and severity filters, and shows alert badges in the navbar and +sidebar. ## Core features -- Live log streaming -- Search with severity filters -- Regex and case-sensitive search modes -- Log download and alert history -- Path traversal protection and input validation +- Live log streaming (single file from the UI, multiple files via the API) +- Full-text search with severity filters, regex and case-sensitive modes +- Background severity alerting with history, independent of the UI stream +- Log download and search-result export (CSV/TXT) +- Path traversal protection, rate limiting, and optional masking of + sensitive log content -## Source +## How it works -See the project README for the full plugin description and installation notes. +The backend consists of four small modules: + +| Module | Responsibility | +| -------------- | ------------------------------------------------------------------------------------------------------- | +| `log_parser` | Single source of truth for parsing OctoPrint, serial, and compact log-line formats. | +| `log_tailer` | `tail -f`-style background thread per streamed file; detects rotation and truncation. | +| `log_searcher` | Streams through files line by line for search, stats, and exports — memory use is bounded by page size. | +| `security` | Filename/path validation, file-size guard, rate limiting, sensitive-data masking. | + +The plugin core (`octoprint_logmonitor/__init__.py`) wires these together: + +- **Live stream** — a tailer per streamed file pushes parsed lines into a + shared buffer, which is flushed to the browser as one batched WebSocket + message per poll interval. +- **Alert monitor** — separate tailers watch the configured log files and + raise `severity_alert` messages whenever a line matches the trigger + levels, even while the Log Monitor tab is closed. +- **REST API** — all routes live under `/plugin/logmonitor`; see the + [REST API reference](rest-api.md). + +## Further reading + +- [Configuration reference](configuration.md) +- [REST API reference](rest-api.md) +- [Troubleshooting](troubleshooting.md) +- [Python API](api/python.md) + +See the project README for installation notes. diff --git a/docs/rest-api.md b/docs/rest-api.md new file mode 100644 index 0000000..1a39ffe --- /dev/null +++ b/docs/rest-api.md @@ -0,0 +1,156 @@ +# REST API Reference + +All endpoints are served under the plugin blueprint: + +```text +/plugin/logmonitor +``` + +Requests go through OctoPrint's normal session authentication and CSRF +protection — call them from the OctoPrint web UI context or with a valid +API key/session. Filenames are validated on every endpoint: only plain +`.log` filenames inside OctoPrint's log folder are accepted (no path +components, no hidden files). + +## Log files + +### `GET /files` + +List available log files. + +```json +{ + "files": [ + { "name": "octoprint.log", "size": 123456, "modified": 1719999999.0 } + ] +} +``` + +### `GET /download/` + +Download a log file as attachment. +Errors: `400` invalid filename, `403` outside log folder, `404` not found. + +## Search + +### `GET /search` + +Search a log file with pagination. + +| Parameter | Default | Description | +| ---------------- | ------------------ | ----------------------------------------------------------- | +| `file` | `default_log_file` | Log filename. | +| `query` | `""` | Free-text or regex query. | +| `levels` | all | Repeatable severity filter (`levels=ERROR&levels=WARNING`). | +| `offset` | `0` | Matches to skip. | +| `limit` | `search_page_size` | Max results (hard cap 1000). | +| `case_sensitive` | `false` | Exact-case matching. | +| `use_regex` | `false` | Treat `query` as a regular expression. | + +```json +{ "results": [], "total": 0, "offset": 0, "limit": 50 } +``` + +`total` counts matches until scanning stopped: the backend stops early once +the requested page plus one look-ahead match is complete, so treat it as +"at least this many". + +Errors: `400` bad parameters, `403` denied, `404` unknown file, +`413` file larger than 1 GiB, `429` rate limit (10 requests/minute/client). + +### `POST /export` + +Export search results (the client sends the results back). + +```json +{ + "results": [ + { "timestamp": "…", "logger": "…", "level": "…", "message": "…" } + ], + "format": "csv" +} +``` + +`format` is `csv` or `txt`. Returns the file as attachment. +Errors: `400` invalid format or more than 1000 entries. + +## Live streaming + +Streamed lines are pushed over OctoPrint's plugin WebSocket as batched +messages (see [Push messages](#push-messages)). + +### `POST /stream/start` + +Start (or switch) the single-file UI stream. Body: `{ "file": "octoprint.log" }` +(defaults to `default_log_file`). Responds with up to 100 initial lines: + +```json +{ "status": "started", "file": "octoprint.log", "initial_lines": [] } +``` + +### `POST /stream/stop` + +Stop the single-file stream. Returns `{"status": "stopped"}` or +`{"status": "not_running"}`. + +### `POST /stream/multi/start` + +Start streaming several files at once (max 20). Body: +`{ "files": ["octoprint.log", "serial.log"] }`. + +```json +{ "status": "multi_started", "started": [], "failed": [], "total_active": 2 } +``` + +Lines from multi-streams carry a `_source_file` field. + +### `POST /stream/multi/stop` + +Stop specific streams or all of them. Body: +`{ "files": ["serial.log"] }` or `{ "stop_all": true }`. + +### `GET /multi-stream` + +List currently active multi-stream files. + +## Alerts + +### `POST /alerts/reset` + +Reset the per-severity alert counters. + +### `GET /alert-history?limit=100` + +Return recent alert entries (newest last, `limit` caps at 500). + +### `POST /alert-history/clear` + +Clear the alert history. + +### `GET /alerts/monitor/status` + +Show the background alert monitor configuration and which files are +actively watched. + +## Debug (require `debug_mode`) + +### `POST /debug/frontend` + +Write a frontend debug event into the OctoPrint server log. +Body: `{ "message": "…", "payload": {} }`. + +### `POST /debug/test-entries` + +Write one test log entry per severity (including `UNKNOWN`) so alert +handling can be verified end to end. + +## Push messages + +The plugin sends these messages via +`OctoPrint.coreui.viewmodels`/`onDataUpdaterPluginMessage` (plugin id +`logmonitor`): + +| `type` | Payload | +| ---------------- | ---------------------------------------------------------------------------------------------------------- | +| `log_lines` | `data`: array of parsed lines (`timestamp`, `logger`, `level`, `message`, `raw`, optional `_source_file`). | +| `severity_alert` | `level`, `count`, `message`, `notification_enabled`, `source_file`. | diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md new file mode 100644 index 0000000..8cb5098 --- /dev/null +++ b/docs/troubleshooting.md @@ -0,0 +1,47 @@ +# Troubleshooting + +## The file dropdown is empty + +- The plugin only lists regular files ending in `.log` inside OctoPrint's + log folder (usually `~/.octoprint/logs`). +- Check that the OctoPrint user can read that folder. + +## Streaming shows no new lines + +- The tailer starts at the **end** of the file: only lines written after + the stream starts appear (plus up to 100 initial context lines). +- New lines are delivered in batches once per poll interval + (`stream_poll_interval_s`, default 5 s) — short delays are expected. +- Rotated and truncated log files are picked up automatically; if a stream + ever looks stuck, stop and restart it. + +## Search returns an error + +| Status | Meaning | Fix | +| ------ | ---------------------------------- | ----------------------------------------------- | +| `400` | Invalid filename, level, or paging | Check query parameters. | +| `403` | File outside the log folder | Only plain filenames in the log folder work. | +| `404` | File does not exist | Refresh the file list. | +| `413` | File larger than 1 GiB | Rotate/trim the log file. | +| `429` | More than 10 searches per minute | Wait a moment; the limit is per client address. | + +## Alerts do not appear + +- Check `alerts_enabled` and that the level is listed in + `severity_triggers` (defaults: WARNING, ERROR, CRITICAL). +- In mode `selected`, only files in `alerts_monitored_logs` are watched — + the **Alert monitor status** panel in the plugin settings shows which + files are currently active. +- Alert toasts additionally require `enable_notifications`. + +## Getting more information + +1. Enable **debug mode** in the plugin settings. +2. Use **Write test entries** in the settings to generate one log entry + per severity and verify the whole pipeline. +3. Check `octoprint.log` for entries from `octoprint.plugins.logmonitor` — + including `[SECURITY]` entries for rejected filenames or rate limits. + +Still stuck? Open a +[GitHub issue](https://github.com/Ajimaru/OctoPrint-LogMonitor/issues) +with your OctoPrint version, plugin version, and relevant log excerpts. diff --git a/mkdocs.yml b/mkdocs.yml index c0983bc..e801e77 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -10,6 +10,9 @@ nav: - Home: index.md - Plugin: - Overview: overview.md + - Configuration: configuration.md + - REST API: rest-api.md + - Troubleshooting: troubleshooting.md - Python API: api/python.md - Project: - Contributing: contributing.md diff --git a/octoprint_logmonitor/__init__.py b/octoprint_logmonitor/__init__.py index 1ad0927..a5014ad 100644 --- a/octoprint_logmonitor/__init__.py +++ b/octoprint_logmonitor/__init__.py @@ -47,6 +47,21 @@ "not_found": ("Log file not found", 404), } +# Hard cap on lines buffered between WebSocket flushes. Bounds memory if +# flushing stalls; must be >= the largest allowed ``max_stream_lines``. +_MAX_BUFFERED_LINES = 10000 + + +def _new_alert_counts() -> dict[str, int]: + """Return a fresh per-severity alert counter mapping.""" + return { + "DEBUG": 0, + "INFO": 0, + "WARNING": 0, + "ERROR": 0, + "CRITICAL": 0, + } + class LogmonitorPlugin( octoprint.plugin.StartupPlugin, @@ -90,6 +105,7 @@ def __init__(self): self._line_buffer = [] self._line_buffer_lock = threading.Lock() self._flush_timer = None + self._flush_timer_lock = threading.Lock() self._runtime_settings_lock = threading.Lock() self._runtime_alert_settings = { "alerts_enabled": True, @@ -119,13 +135,7 @@ def on_after_startup(self): # Reset alert counts with self._alert_lock: - self._alert_counts = { - "DEBUG": 0, - "INFO": 0, - "WARNING": 0, - "ERROR": 0, - "CRITICAL": 0, - } + self._alert_counts = _new_alert_counts() # Start independent alert monitoring (not tied to UI live streaming) self._restart_alert_monitoring() @@ -162,6 +172,10 @@ def on_shutdown(self): """Clean shutdown of background threads.""" self._logger.info("Log Monitor Plugin shutting down") + self._stop_flush_timer() + with self._line_buffer_lock: + self._line_buffer.clear() + # Stop main tailer if running if self._tailer and self._tailer.is_running(): self._tailer.stop() @@ -234,7 +248,10 @@ def clamp_int_setting(key, default, minimum, maximum): clamp_int_setting("max_stream_lines", 500, 100, 10000) clamp_int_setting("search_page_size", 50, 10, 500) - clamp_int_setting("max_alert_history", 100, 10, 1000) + # Keep in sync with the runtime cap (MAX_HISTORY_LIMIT). + clamp_int_setting( + "max_alert_history", 100, 10, MAX_HISTORY_LIMIT + ) alerts_enabled = plugin_data.get("alerts_enabled") if isinstance(alerts_enabled, str): @@ -359,23 +376,30 @@ def is_template_autoescaped(self): # type: ignore[override] """Enable Jinja autoescaping for all plugin templates.""" return True + def _list_log_files(self) -> list[tuple[str, str]]: + """Return sorted ``(filename, filepath)`` pairs of available logs. + + Scans the OctoPrint log folder for regular ``.log`` files. + """ + log_dir = self._get_logs_base_folder() + if not os.path.isdir(log_dir): + return [] + + entries = [] + for filename in sorted(os.listdir(log_dir)): + filepath = os.path.join(log_dir, filename) + if os.path.isfile(filepath) and filename.endswith(".log"): + entries.append((filename, filepath)) + + return entries + def _get_available_log_filenames(self): """Return sorted list of available .log filenames. Scans the OctoPrint log folder. """ try: - log_dir = self._get_logs_base_folder() - if not os.path.exists(log_dir): - return [] - - files = [] - for filename in os.listdir(log_dir): - filepath = os.path.join(log_dir, filename) - if os.path.isfile(filepath) and filename.endswith(".log"): - files.append(filename) - - return sorted(files) + return [filename for filename, _ in self._list_log_files()] except Exception as e: self._logger.error( f"Error listing log filenames for template vars: {e}" @@ -413,22 +437,14 @@ def get_log_files(self): {"files": [], "error": "Log directory not found"} ) - files = [] - for filename in os.listdir(log_dir): - filepath = os.path.join(log_dir, filename) - - # Only include .log files - if os.path.isfile(filepath) and filename.endswith(".log"): - files.append( - { - "name": filename, - "size": os.path.getsize(filepath), - "modified": os.path.getmtime(filepath), - } - ) - - # Sort by name - files.sort(key=lambda x: x["name"]) + files = [ + { + "name": filename, + "size": os.path.getsize(filepath), + "modified": os.path.getmtime(filepath), + } + for filename, filepath in self._list_log_files() + ] return flask.jsonify({"files": files}) @@ -479,13 +495,13 @@ def search_logs(self): ) # Validate and clamp offset / limit + try: + default_limit = int(self._settings.get(["search_page_size"])) + except (ValueError, TypeError): + default_limit = 50 try: offset = int(flask.request.args.get("offset", 0)) - limit = int( - flask.request.args.get( - "limit", str(self._settings.get(["search_page_size"])) - ) - ) + limit = int(flask.request.args.get("limit", default_limit)) except (ValueError, TypeError): return ( flask.jsonify( @@ -605,11 +621,11 @@ def start_stream(self): # Start tailing if self._tailer.start(): - # Start batch-flush timer - if self._flush_timer: - self._flush_timer.cancel() - with self._line_buffer_lock: - self._line_buffer.clear() + # Reset the batch buffer, unless multi-stream tailers are + # still feeding it. + if not self._active_tailers: + with self._line_buffer_lock: + self._line_buffer.clear() self._start_flush_timer() # Send initial lines @@ -648,17 +664,21 @@ def start_stream(self): def stop_stream(self): """Stop log streaming.""" try: - if self._flush_timer: - self._flush_timer.cancel() - self._flush_timer = None - with self._line_buffer_lock: - self._line_buffer.clear() if self._tailer and self._tailer.is_running(): self._tailer.stop() self._tailer = None - return flask.jsonify({"status": "stopped"}) + status = "stopped" else: - return flask.jsonify({"status": "not_running"}) + status = "not_running" + + # Keep the flush timer alive while multi-stream tailers still + # feed the shared line buffer. + if not self._active_tailers: + self._stop_flush_timer() + with self._line_buffer_lock: + self._line_buffer.clear() + + return flask.jsonify({"status": status}) except Exception as e: self._logger.error(f"Error stopping stream: {e}") @@ -669,7 +689,7 @@ def stop_stream(self): ) @no_firstrun_access def start_multi_stream(self): - """Start streaming multiple log files simultaneously (NEW).""" + """Start streaming multiple log files simultaneously.""" try: data = flask.request.get_json(silent=True) or {} files = data.get("files", []) @@ -754,6 +774,9 @@ def callback(line): {"file": filename, "error": "Failed to start"} ) + if started_files: + self._ensure_flush_timer() + return flask.jsonify( { "status": "multi_started", @@ -775,7 +798,7 @@ def callback(line): ) @no_firstrun_access def stop_multi_stream(self): - """Stop streaming specific log files (NEW).""" + """Stop streaming specific log files.""" try: data = flask.request.get_json(silent=True) or {} files = data.get("files", []) @@ -786,15 +809,18 @@ def stop_multi_stream(self): return flask.jsonify({"error": "files must be a list"}), 400 if stop_all: + stopped_count = 0 for filename, tailer in list(self._active_tailers.items()): try: tailer.stop() del self._active_tailers[filename] + stopped_count += 1 except Exception as e: self._logger.error(f"Error stopping {filename}: {e}") + self._stop_flush_timer_if_idle() return flask.jsonify( - {"status": "all_stopped", "total_stopped": len(files)} + {"status": "all_stopped", "total_stopped": stopped_count} ) else: stopped_files = [] @@ -814,6 +840,7 @@ def stop_multi_stream(self): f"Error stopping {filename}: {e}" ) + self._stop_flush_timer_if_idle() return flask.jsonify( { "status": "multi_stopped", @@ -832,13 +859,7 @@ def reset_alerts(self): """Reset severity alert counters.""" try: with self._alert_lock: - self._alert_counts = { - "DEBUG": 0, - "INFO": 0, - "WARNING": 0, - "ERROR": 0, - "CRITICAL": 0, - } + self._alert_counts = _new_alert_counts() return flask.jsonify({"status": "reset"}) @@ -1287,39 +1308,76 @@ def _write_unknown_debug_test_log(self, message: str) -> None: f"Failed to write UNKNOWN debug test log entry: {e}" ) + def _has_active_streams(self) -> bool: + """Return True while any UI-facing tailer is delivering lines.""" + if self._tailer and self._tailer.is_running(): + return True + return bool(self._active_tailers) + def _start_flush_timer(self): - """Start the periodic line-buffer flush timer.""" + """(Re)start the periodic line-buffer flush timer.""" interval = self._get_stream_poll_interval_seconds() - self._flush_timer = threading.Timer(interval, self._flush_line_buffer) - self._flush_timer.daemon = True - self._flush_timer.start() + with self._flush_timer_lock: + if self._flush_timer is not None: + self._flush_timer.cancel() + self._flush_timer = threading.Timer( + interval, self._flush_line_buffer + ) + self._flush_timer.daemon = True + self._flush_timer.start() + + def _ensure_flush_timer(self): + """Start the flush timer only if none is currently scheduled. + + Lazy safety net: guarantees buffered lines are eventually delivered + no matter which code path (UI stream, multi-stream, auto-start) + started a tailer. + """ + with self._flush_timer_lock: + if self._flush_timer is not None: + return + self._start_flush_timer() + + def _stop_flush_timer(self): + """Cancel the flush timer if one is scheduled.""" + with self._flush_timer_lock: + if self._flush_timer is not None: + self._flush_timer.cancel() + self._flush_timer = None + + def _stop_flush_timer_if_idle(self): + """Stop the flush timer and drop the buffer once no tailer is left.""" + if self._has_active_streams(): + return + self._stop_flush_timer() + with self._line_buffer_lock: + self._line_buffer.clear() def _flush_line_buffer(self): """Flush buffered lines as a single batch WebSocket message.""" with self._line_buffer_lock: - if not self._line_buffer: - # Reschedule even if empty, as long as streaming is active - if ( - self._tailer - and self._tailer.is_running() - or self._active_tailers - ): - self._start_flush_timer() - return batch = self._line_buffer[:] self._line_buffer.clear() - max_lines = self._settings.get(["max_stream_lines"]) - if len(batch) > max_lines: - batch = batch[-max_lines:] + if batch: + try: + max_lines = int(self._settings.get(["max_stream_lines"])) + except (TypeError, ValueError): + max_lines = 500 + if len(batch) > max_lines: + batch = batch[-max_lines:] - self._plugin_manager.send_plugin_message( - self._identifier, {"type": "log_lines", "data": batch} - ) + self._plugin_manager.send_plugin_message( + self._identifier, {"type": "log_lines", "data": batch} + ) - # Reschedule - if self._tailer and self._tailer.is_running() or self._active_tailers: + # Reschedule while streaming is active; otherwise clear the timer + # slot so _ensure_flush_timer can restart it later. + if self._has_active_streams(): self._start_flush_timer() + else: + with self._flush_timer_lock: + self._flush_timer = None def _get_alert_monitor_files(self): """Resolve list of log files that should drive severity alerts.""" @@ -1615,9 +1673,17 @@ def _handle_log_line(self, parsed_line): else: send_line = parsed_line - # Buffer line for batched WebSocket delivery + # Buffer line for batched WebSocket delivery; cap the buffer so + # memory stays bounded even if flushing stalls. with self._line_buffer_lock: self._line_buffer.append(send_line) + overflow = len(self._line_buffer) - _MAX_BUFFERED_LINES + if overflow > 0: + del self._line_buffer[:overflow] + + # Lazy safety net: whoever produces lines guarantees a flush + # timer exists (covers auto-start and multi-stream paths). + self._ensure_flush_timer() except Exception as e: self._logger.error(f"Error handling log line: {e}") diff --git a/octoprint_logmonitor/_version.py b/octoprint_logmonitor/_version.py index ff81f84..38ff8c1 100644 --- a/octoprint_logmonitor/_version.py +++ b/octoprint_logmonitor/_version.py @@ -1,3 +1,3 @@ """Single source of truth for the plugin version used by dev tooling.""" -VERSION = "0.2.3" +VERSION = "0.2.4" diff --git a/octoprint_logmonitor/log_parser.py b/octoprint_logmonitor/log_parser.py new file mode 100644 index 0000000..6460e38 --- /dev/null +++ b/octoprint_logmonitor/log_parser.py @@ -0,0 +1,138 @@ +"""Shared log-line parsing for the Log Monitor plugin. + +Single source of truth for the log formats understood by both the live +tailer (:mod:`.log_tailer`) and the search backend (:mod:`.log_searcher`), +so that streaming and searching always classify lines identically. + +Supported formats (tried in order): + +1. Standard OctoPrint format:: + + YYYY-MM-DD HH:MM:SS[,ms] - LOGGER - LEVEL - MESSAGE + +2. Simple serial-log format (level inferred from message keywords):: + + YYYY-MM-DD HH:MM:SS[,ms] - MESSAGE + +3. Compact format without ``" - "`` separators:: + + YYYY-MM-DD HH:MM:SS[,ms]LEVEL LOGGER MESSAGE + +4. Serial I/O format from the virtual printer:: + + YYYY-MM-DD HH:MM:SS[,ms] >>> MESSAGE + +Anything else is returned with level ``UNKNOWN`` and the raw line as the +message. +""" + +import re +from typing import Any + +#: Timestamp prefix shared by all supported formats. +_TIMESTAMP = r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:,\d{3})?" + +#: Standard OctoPrint log format: +#: ``YYYY-MM-DD HH:MM:SS[,ms] - LOGGER - LEVEL - MESSAGE``. +#: The logger group is non-greedy so hyphenated logger names +#: (e.g. ``octoprint.plugins.my-plugin``) parse correctly. +LOG_PATTERN = re.compile( + rf"^({_TIMESTAMP})\s+-\s+" + r"(.+?)\s+-\s+" + r"(DEBUG|INFO|WARNING|ERROR|CRITICAL)\s+-\s+" + r"(.+)$" +) + +#: Serial log often uses: ``YYYY-MM-DD HH:MM:SS[,ms] - MESSAGE``. +SIMPLE_LOG_PATTERN = re.compile(rf"^({_TIMESTAMP})\s+-\s+(.+)$") + +#: Compact lines without the usual ``" - "`` separators: +#: ``YYYY-MM-DD HH:MM:SS[,ms]LEVEL LOGGER MESSAGE``. +COMPACT_LOG_PATTERN = re.compile( + rf"^({_TIMESTAMP})" + r"\s*(DEBUG|INFO|WARNING|ERROR|CRITICAL)\s+" + r"([A-Za-z0-9_.:-]+)\s+(.+)$" +) + +#: Virtual printer serial I/O lines: +#: ``YYYY-MM-DD HH:MM:SS[,ms] >>> MESSAGE``. +SERIAL_IO_PATTERN = re.compile(rf"^({_TIMESTAMP})\s+(>>>|<<<)\s+(.+)$") + +#: Keywords used to infer a severity level from free-form serial-log +#: messages, checked in order of decreasing severity. +_INFERRED_LEVELS = ("CRITICAL", "ERROR", "WARNING", "DEBUG") + + +def parse_line(line: str) -> dict[str, Any]: + """Parse a raw log line into a structured dictionary. + + Args: + line: Raw log line (trailing newline is stripped, tabs are + normalised to four spaces). + + Returns: + Dictionary with the keys ``timestamp``, ``logger``, ``level``, + ``message`` and ``raw``. Lines that match no known format get + level ``UNKNOWN`` with empty timestamp/logger fields. + """ + line = line.rstrip("\n\r") + raw_line = line.replace("\t", " ") + + match = LOG_PATTERN.match(raw_line) + if match: + return { + "timestamp": match.group(1), + "logger": match.group(2).strip(), + "level": match.group(3), + "message": match.group(4), + "raw": raw_line, + } + + simple_match = SIMPLE_LOG_PATTERN.match(raw_line) + if simple_match: + message = simple_match.group(2).strip() + level = "INFO" + upper_message = message.upper() + for candidate in _INFERRED_LEVELS: + if candidate in upper_message: + level = candidate + break + + return { + "timestamp": simple_match.group(1), + "logger": "serial.log", + "level": level, + "message": message, + "raw": raw_line, + } + + compact_match = COMPACT_LOG_PATTERN.match(raw_line) + if compact_match: + return { + "timestamp": compact_match.group(1), + "logger": compact_match.group(3).strip(), + "level": compact_match.group(2), + "message": compact_match.group(4), + "raw": raw_line, + } + + serial_match = SERIAL_IO_PATTERN.match(raw_line) + if serial_match: + direction = serial_match.group(2) + message = serial_match.group(3).strip() + return { + "timestamp": serial_match.group(1), + "logger": "serial.log", + "level": "INFO", + "message": f"{direction} {message}", + "raw": raw_line, + } + + # Line doesn't match any known format, return as-is + return { + "timestamp": "", + "logger": "", + "level": "UNKNOWN", + "message": raw_line, + "raw": raw_line, + } diff --git a/octoprint_logmonitor/log_searcher.py b/octoprint_logmonitor/log_searcher.py index 34bc05e..39f7371 100644 --- a/octoprint_logmonitor/log_searcher.py +++ b/octoprint_logmonitor/log_searcher.py @@ -1,21 +1,25 @@ """Log Searcher Module. Provides efficient log file searching with pagination and severity filtering. -Memory-efficient implementation that streams through large log files. +Memory-efficient implementation that streams through large log files +line by line instead of loading them into memory. """ import csv import io import os import re +from collections import deque from typing import Any, ClassVar, Optional +from .log_parser import parse_line + class LogSearcher: """Efficient log file searcher with pagination support. Features: - - Memory-efficient line-by-line reading + - Memory-efficient line-by-line streaming (never loads the whole file) - Free-text search (case-insensitive) - Severity level filtering - Pagination support @@ -23,22 +27,6 @@ class LogSearcher: - Regex search mode (optional) """ - # OctoPrint log format: YYYY-MM-DD HH:MM:SS,ms - LOGGER - LEVEL - MESSAGE - LOG_PATTERN = re.compile( - r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3})\s+-\s+" - r"([^\-]+)\s+-\s+" - r"(DEBUG|INFO|WARNING|ERROR|CRITICAL)\s+-\s+" - r"(.+)$" - ) - - # Compact format seen in some environments: - # YYYY-MM-DD HH:MM:SS,msLEVEL LOGGER MESSAGE - COMPACT_LOG_PATTERN = re.compile( - r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3})" - r"\s*(DEBUG|INFO|WARNING|ERROR|CRITICAL)\s+" - r"([A-Za-z0-9_.:-]+)\s+(.+)$" - ) - VALID_LEVELS: ClassVar[set[str]] = { "DEBUG", "INFO", @@ -71,6 +59,12 @@ def search( ) -> dict[str, Any]: """Search log file for matching entries. + The file is streamed line by line; memory usage is bounded by + ``limit`` and ``context_lines``, not by file size. Scanning stops + early once the requested page (plus one look-ahead match) is + complete, so ``total`` is exact only up to that point and should be + read as "at least this many matches". + Args: filepath: Path to the log file query: Search query (free text or regex) @@ -84,7 +78,7 @@ def search( Returns: Dictionary with: - results: List of matching log entries - - total: Total number of matches found + - total: Number of matches found before scanning stopped - offset: Current offset - limit: Current limit """ @@ -132,50 +126,68 @@ def search( "error": f"Invalid search pattern: {e}", } - # Search the file + # Stream through the file try: - results = [] + results: list[dict[str, Any]] = [] total_matches = 0 current_match = 0 + # Sliding window of parsed lines preceding the current one. + before_buffer: Optional[deque] = ( + deque(maxlen=context_lines) if context_lines > 0 else None + ) + # Matches still waiting for their after-context to fill up: + # list of [entry, remaining_line_count] pairs. + pending_after: list[list[Any]] = [] + with open(filepath, encoding="utf-8", errors="replace") as f: - lines = f.readlines() - - # Process lines - for i, line in enumerate(lines): - parsed = self._parse_line(line) - - # Check if line matches filters - if self._matches_filters( - parsed, search_pattern, allowed_levels - ): - total_matches += 1 - - # Check if we should include this match (pagination) - if current_match >= offset and len(results) < limit: - # Add the match - match_entry = parsed.copy() - - # Add context lines if requested - if context_lines > 0: - ctx = self._get_context_lines - match_entry["context_before"] = ctx( - lines, i, context_lines, before=True - ) - match_entry["context_after"] = ctx( - lines, i, context_lines, before=False - ) - - results.append(match_entry) - - current_match += 1 - - # Early exit if we have enough results - if ( - len(results) >= limit - and current_match > offset + limit + for line in f: + parsed = self._parse_line(line) + + # Feed after-context of earlier matches first, so the + # match line itself is not part of its own context. + if pending_after: + for item in pending_after: + item[0]["context_after"].append(parsed) + item[1] -= 1 + pending_after = [ + item for item in pending_after if item[1] > 0 + ] + + if self._matches_filters( + parsed, search_pattern, allowed_levels ): - break + total_matches += 1 + + # Include this match on the requested page + if current_match >= offset and len(results) < limit: + match_entry = parsed.copy() + + if context_lines > 0: + match_entry["context_before"] = list( + before_buffer or () + ) + match_entry["context_after"] = [] + pending_after.append( + [match_entry, context_lines] + ) + + results.append(match_entry) + + current_match += 1 + + # Early exit once the page is full, one extra match + # confirmed (so callers can detect further pages) and + # all after-context collected. + if ( + len(results) >= limit + and current_match > offset + limit + and not pending_after + ): + break + + if before_buffer is not None: + before_buffer.append(parsed) return { "results": results, @@ -202,38 +214,10 @@ def _parse_line(self, line: str) -> dict[str, Any]: line: Raw log line Returns: - Dictionary with parsed fields + Dictionary with parsed fields (see + :func:`octoprint_logmonitor.log_parser.parse_line`) """ - line = line.rstrip("\n\r") - - match = self.LOG_PATTERN.match(line) - - if match: - return { - "timestamp": match.group(1), - "logger": match.group(2).strip(), - "level": match.group(3), - "message": match.group(4), - "raw": line, - } - - compact_match = self.COMPACT_LOG_PATTERN.match(line) - if compact_match: - return { - "timestamp": compact_match.group(1), - "logger": compact_match.group(3).strip(), - "level": compact_match.group(2), - "message": compact_match.group(4), - "raw": line, - } - # Line doesn't match expected format - return { - "timestamp": "", - "logger": "", - "level": "UNKNOWN", - "message": line, - "raw": line, - } + return parse_line(line) def _matches_filters( self, @@ -264,34 +248,6 @@ def _matches_filters( or search_pattern.search(parsed["raw"]) ) - def _get_context_lines( - self, lines: list[str], index: int, count: int, before: bool = True - ) -> list[dict[str, Any]]: - """Get context lines before or after a match. - - Args: - lines: All lines from the file - index: Index of the match - count: Number of context lines to get - before: If True, get lines before; if False, get lines after - - Returns: - List of parsed context line dictionaries - """ - if before: - start = max(0, index - count) - end = index - else: - start = index + 1 - end = min(len(lines), index + 1 + count) - - context = [] - for i in range(start, end): - if 0 <= i < len(lines): - context.append(self._parse_line(lines[i])) - - return context - def get_file_stats(self, filepath: str) -> dict[str, Any]: """Get statistics about a log file. diff --git a/octoprint_logmonitor/log_tailer.py b/octoprint_logmonitor/log_tailer.py index b585688..cd142a1 100644 --- a/octoprint_logmonitor/log_tailer.py +++ b/octoprint_logmonitor/log_tailer.py @@ -5,52 +5,27 @@ """ import os -import re import threading import time from typing import Any, Callable, Optional +from .log_parser import parse_line + +#: Block size used when reading a file backwards in +#: :meth:`LogTailer.get_last_n_lines`. +_TAIL_BLOCK_SIZE = 8192 + class LogTailer: """Background thread that continuously monitors a log file for new lines. Features: - Thread-safe start/stop - - Handles file rotation + - Handles file rotation (rename/recreate and copy-truncate) - Parses OctoPrint log format - Calls callback for each new line """ - # pylint: disable=too-many-instance-attributes - - # OctoPrint log format: YYYY-MM-DD HH:MM:SS[,ms] - LOGGER - LEVEL - MESSAGE - LOG_PATTERN = re.compile( - r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:,\d{3})?)\s+-\s+" - r"([^\-]+)\s+-\s+" - r"(DEBUG|INFO|WARNING|ERROR|CRITICAL)\s+-\s+" - r"(.+)$" - ) - - # Serial log often uses: YYYY-MM-DD HH:MM:SS,ms - MESSAGE - SIMPLE_LOG_PATTERN = re.compile( - r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:,\d{3})?)\s+-\s+(.+)$" - ) - - # Some environments log compact lines without the usual " - " separators: - # YYYY-MM-DD HH:MM:SS,msLEVEL LOGGER MESSAGE - COMPACT_LOG_PATTERN = re.compile( - r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:,\d{3})?)" - r"\s*(DEBUG|INFO|WARNING|ERROR|CRITICAL)\s+" - r"([A-Za-z0-9_.:-]+)\s+(.+)$" - ) - - # Virtual printer serial lines often use: YYYY-MM-DD HH:MM:SS,ms >>> - # MESSAGE - SERIAL_IO_PATTERN = re.compile( - r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:,\d{3})?)" - r"\s+(>>>|<<<)\s+(.+)$" - ) - def __init__( self, filepath: str, @@ -216,14 +191,24 @@ def _run(self): self._logger.debug("LogTailer thread exiting") def _check_rotation(self) -> bool: - """Check if the log file has been rotated. + """Check if the log file has been rotated or truncated. + + Detects both rotation styles used by logrotate-like tools: + + - rename/recreate: the path now points to a different inode + - copy-truncate: same inode, but the file shrank below the + current read position Returns: - True if rotation detected, False otherwise + True if rotation/truncation detected, False otherwise """ try: - current_inode = os.stat(self._filepath).st_ino - return current_inode != self._file_inode + stat = os.stat(self._filepath) + if stat.st_ino != self._file_inode: + return True + if self._file is not None and stat.st_size < self._file.tell(): + return True + return False except OSError: return False @@ -254,98 +239,44 @@ def _parse_line(self, line: str) -> dict[str, Any]: line: Raw log line Returns: - Dictionary with parsed fields + Dictionary with parsed fields (see + :func:`octoprint_logmonitor.log_parser.parse_line`) """ - line = line.rstrip("\n\r") - raw_line = line.replace("\t", " ") - - match = self.LOG_PATTERN.match(raw_line) - - if match: - message = match.group(4).replace("\t", " ") - return { - "timestamp": match.group(1), - "logger": match.group(2).strip(), - "level": match.group(3), - "message": message, - "raw": raw_line, - } - - simple_match = self.SIMPLE_LOG_PATTERN.match(raw_line) - if simple_match: - message = simple_match.group(2).strip() - level = "INFO" - upper_message = message.upper() - if "CRITICAL" in upper_message: - level = "CRITICAL" - elif "ERROR" in upper_message: - level = "ERROR" - elif "WARNING" in upper_message: - level = "WARNING" - elif "DEBUG" in upper_message: - level = "DEBUG" - - return { - "timestamp": simple_match.group(1), - "logger": "serial.log", - "level": level, - "message": message, - "raw": raw_line, - } - - compact_match = self.COMPACT_LOG_PATTERN.match(raw_line) - if compact_match: - return { - "timestamp": compact_match.group(1), - "logger": compact_match.group(3).strip(), - "level": compact_match.group(2), - "message": compact_match.group(4), - "raw": raw_line, - } - - serial_match = self.SERIAL_IO_PATTERN.match(raw_line) - if serial_match: - direction = serial_match.group(2) - message = serial_match.group(3).strip() - return { - "timestamp": serial_match.group(1), - "logger": "serial.log", - "level": "INFO", - "message": f"{direction} {message}", - "raw": raw_line, - } - - # Line doesn't match expected format, return as-is - return { - "timestamp": "", - "logger": "", - "level": "UNKNOWN", - "message": raw_line, - "raw": raw_line, - } + return parse_line(line) def get_last_n_lines(self, n: int = 100) -> list: """Read the last N lines from the log file. + Reads the file backwards in blocks, so only roughly the requested + amount of data is loaded regardless of total file size. + Args: n: Number of lines to read Returns: List of parsed log line dictionaries """ - if not os.path.exists(self._filepath): + if n <= 0 or not os.path.exists(self._filepath): return [] try: - with open(self._filepath, encoding="utf-8", errors="replace") as f: - # Read all lines - lines = f.readlines() - - # Get last N lines - last_lines = lines[-n:] if len(lines) > n else lines - - # Parse each line - return [self._parse_line(line) for line in last_lines] + with open(self._filepath, "rb") as f: + f.seek(0, os.SEEK_END) + pos = f.tell() + data = b"" + + # Read blocks from the end until enough newlines collected + # (n + 1 newlines guarantee n complete lines). + while pos > 0 and data.count(b"\n") <= n: + read_size = min(_TAIL_BLOCK_SIZE, pos) + pos -= read_size + f.seek(pos) + data = f.read(read_size) + data + + text = data.decode("utf-8", errors="replace") + last_lines = text.splitlines()[-n:] + + return [self._parse_line(line) for line in last_lines] except OSError as e: if self._logger: diff --git a/octoprint_logmonitor/security.py b/octoprint_logmonitor/security.py index 7e1006b..7dd15b8 100644 --- a/octoprint_logmonitor/security.py +++ b/octoprint_logmonitor/security.py @@ -254,12 +254,15 @@ def __init__(self, max_calls: int, period: float) -> None: self._period = period self._clients: dict[str, list[float]] = {} self._lock = threading.Lock() + self._last_cleanup = time.monotonic() def is_allowed(self, client_key: str) -> bool: """Check whether *client_key* is within the rate limit. Calling this method counts as one request attempt regardless of the - return value. + return value. Fully-expired client entries are pruned automatically + once per sliding-window period, so the tracking dict cannot grow + without bound. Args: client_key: An opaque string identifying the caller (e.g. IP). @@ -270,6 +273,10 @@ def is_allowed(self, client_key: str) -> bool: """ now = time.monotonic() with self._lock: + if now - self._last_cleanup >= self._period: + self._cleanup_locked(now) + self._last_cleanup = now + timestamps = self._clients.get(client_key, []) # Evict expired timestamps timestamps = [t for t in timestamps if now - t < self._period] @@ -282,11 +289,16 @@ def is_allowed(self, client_key: str) -> bool: def cleanup(self) -> None: """Remove all fully-expired client entries to free memory.""" - now = time.monotonic() with self._lock: - for key in list(self._clients.keys()): - self._clients[key] = [ - t for t in self._clients[key] if now - t < self._period - ] - if not self._clients[key]: - del self._clients[key] + self._cleanup_locked(time.monotonic()) + + def _cleanup_locked(self, now: float) -> None: + """Prune expired entries; caller must hold ``self._lock``.""" + for key in list(self._clients.keys()): + remaining = [ + t for t in self._clients[key] if now - t < self._period + ] + if remaining: + self._clients[key] = remaining + else: + del self._clients[key] diff --git a/octoprint_logmonitor/static/js/logmonitor.js b/octoprint_logmonitor/static/js/logmonitor.js index d3a5604..87b8051 100644 --- a/octoprint_logmonitor/static/js/logmonitor.js +++ b/octoprint_logmonitor/static/js/logmonitor.js @@ -280,11 +280,10 @@ $(() => { self.lastSearchAt = 0; self.pendingSearchRequest = null; - // NEW: Advanced search and export features + // Advanced search and export features self.useRegex = ko.observable(false); self.caseSensitive = ko.observable(false); self.alertHistory = ko.observableArray([]); - self.autoStartEnabled = ko.observable(false); self.historySummary = ko.pureComputed(() => { var count = self.alertHistory().length; return ngettext( @@ -458,15 +457,6 @@ $(() => { ); if (!target.length) return; - function escapeHtml(value) { - return String(value) - .replace(/&/g, "&") - .replace(//g, ">") - .replace(/"/g, """) - .replace(/'/g, "'"); - } - function renderLogList(logs) { if (!logs || logs.length === 0) { return 'none'; @@ -937,7 +927,7 @@ $(() => { }); }; - // NEW: Export functions + // Export functions self.exportResults = function (format) { if (self.searchResults().length === 0) { alert("No results to export"); @@ -971,14 +961,14 @@ $(() => { }); }; - // NEW: Download log file + // Download log file self.downloadLogFile = function (filename) { var url = pluginBaseUrl + "/download/" + encodeURIComponent(filename); window.location.assign(url); }; - // NEW: Load alert history + // Load alert history self.loadAlertHistory = function () { pluginAjax({ url: pluginBaseUrl + "/alert-history", @@ -992,7 +982,7 @@ $(() => { }); }; - // NEW: Clear alert history + // Clear alert history self.clearAlertHistory = function () { if (!confirm("Clear all alert history?")) return; @@ -1006,7 +996,7 @@ $(() => { }); }; - // NEW: Auto-start streaming on page load + // Auto-start streaming on page load self.onStartup = function () { // Load alert history self.loadAlertHistory(); @@ -1087,10 +1077,6 @@ $(() => { } }; - self.handleLogLine = function (line) { - lineBuffer.push(line); - }; - self.handleAlert = function (alert) { var level = String((alert && alert.level) || "").toUpperCase(); if (!level) { @@ -1127,22 +1113,6 @@ $(() => { type: pnotifyType, }); } - - // NEW: Play sound if available (optional) - if (alert.notification_enabled) { - try { - // Use a small beep sound encoded in base64 - var audio = new Audio( - "data:audio/wav;base64,UklGRiYAAABXQVZFZm10IBAAAAABAAEAQB8AAAB9AAACABAAZGF0YQIAAAAAAA==", - ); - audio.volume = 0.5; - audio.play().catch(() => { - // Sound playback failed, continue silently - }); - } catch (e) { - // Audio not supported - } - } }; self.scrollToBottom = function () { diff --git a/octoprint_logmonitor/templates/logmonitor_settings.jinja2 b/octoprint_logmonitor/templates/logmonitor_settings.jinja2 index 86546b3..46f6ab5 100644 --- a/octoprint_logmonitor/templates/logmonitor_settings.jinja2 +++ b/octoprint_logmonitor/templates/logmonitor_settings.jinja2 @@ -222,7 +222,7 @@ {{ _("Maximum number of alert history entries to keep.") }} diff --git a/octoprint_logmonitor/translations/de/LC_MESSAGES/messages.mo b/octoprint_logmonitor/translations/de/LC_MESSAGES/messages.mo index 438fa0c7c8ebceb99d823181258cdad7006a5914..dacabb958ce305ee36d2499125d6352640512618 100644 GIT binary patch delta 2045 zcmY+^Urfzm9LMo*B$c8=M2b=&q0%3zC`FNf9UMt(7KO0TxR8tAn9XdAIX7mE%>{Qf ztQlrD|Jj&@S#GQ`nHjdmW;XB7>FL6=eb4K8e*d2D^Y7d&Jyw1)-t)}t`7nMckB6I$ z!Y3Gy@6d}^Jw>C2_{GLF|5ZaxEs}R5S7Rc9Eshij(Ra4zoQb*AZsO3gb}!41jE;e z7jr=)3h+~mP40oSIDz&>OvXE|-GfTBA9FB*-t^vFWU{Os!?6SPo`;OV&Y@=X5^4r+ z>V~H15h}xe_dq0f^VZ8NHaov5ka>)LlvBY%KOtQ*PAKB5Nr!x_dy`mPVv zpO;3Zf=VIo!u`mz)`!fR{c;ZBD;hy8lA|R!(@{&9i{tSKYKbnO66`{~r>v-2H0pjL zX41dqQc)%isEpgN7CTTcK11Dqjpg_mH3OLpqZD&d9k*dM9>E5DfqE{Bmv@Aj<>6S` z=f{{O;SEfne|tq`A{V~68xd@MC6b2PT-i7W{piQT*obei0Q32(Hq&<02=^d4+Ckie zr%;=&AIZu7Ag@|1)38v-Zwi%4Y(|abGET#LI0O4|D#j-ajGzRyM1It!+lV}3XHXq= zqDJ0@O6V?XKre71_Mj3@rZZ0?OsAsbRE3kV74^ZRsAG2l=i+!-VhYQNMgtwJxC9c6$sF7YoeX!H{5S3sL zYD#}1`_#heMFSXvx}S%Oum%s|3DonW*#LSzJ&E~OC65d0r~1Tesr4<*u;=H8jsIWKTGtSoLd`}Y zq0vq!W)Uiji6UYpkw-KT8wm0ZB?da*woDZYGjD4{wSi6Ps-9)J+7QekN(qg;fKVwX zbUMli?GY87hQXrgUhf*(Z1V|C^gg~ z@hY)u$TWU>s+e>**2jgnvJZWZ7EJ^ZV3i_1w#XCtAfXUX~8UC QR`9AXA*|@yW8a>bfAHR?`2YX_ delta 1609 zcmYk+TS!zv9LMny?`D>6rD^GA7qwbDZLZQP>ROPNq;^4~q&7UMP+FUIfpnqXQli+< zhad}r9*Q7@Kr+M!yO2>3MLlE`K?K%Amj~(k{o#3NS&YYS5f6mP5s~j#nKQC5$uhB-J3y_k*VxCEQ98pGIt57C2}@y0NOsm5g7inDQd zya}6~6xy5)qd1rPxZ_J)PyHj7;*tbo7GM+RVkc_i0aPHvn1ZiR6Me)Y{EiB|AaN#; zG9)%rl}P@|xP}I0v_&GDt<5OqOFl>J|Dh1A9@g=o%`(yQt@4 zh)#i|pzdd50rMLl1x2zK6>$jbu?O|wQ|JC`tfW4LS^*EEm7xzcaR@hIFYdZzsNJ8-kzy*7k2+m`E&-jtItm-`0xFXin1^3*B`zTB6&OHe(8`5XH9e@! z+J{=w2dIfAQJH^01vG_9=obbsfzAqeGlrF60|gzYqnLyJ$lu)IqGR_2OE58g=9L6c z18l+7xDB-@!l>^=9}>H{j>~WawZiX^7|d_yzAJKa9Z#V$eTEuv z((xNAzy!{wmNW<17G^CfflAci<7pg0^{*gG^>4^z{Z-gUgC^=gy}NG5bJ#|G z5Z#za8v4+z#2TzY1sp*QJcx8Px3LH(kYr618%zBbVlysx>SqHKv?Tr5h&NHYK8CM` zj!z2e1JcN)4!f`w$5F?#Fnj2J{7BM@9i9y#JJ{LQ(eBw8?6m!EujMWFSU!(c^SwkOx`Znl$ZgY7L{!4})I!ww!&i@U70w(?+GVMnN?Jksb|9r=@16y4Q% lAmVc^&DdnO+aZQ+_EeqpyQ_lx?SpP_;o9P%ORgiy{{Vr>> M105") + + self.assertEqual(parsed["logger"], "serial.log") + self.assertEqual(parsed["level"], "INFO") + self.assertEqual(parsed["message"], ">>> M105") + + def test_parse_unknown_line(self): + """Unparsable lines fall back to UNKNOWN with raw message.""" + parsed = parse_line("random text without timestamp") + + self.assertEqual(parsed["level"], "UNKNOWN") + self.assertEqual(parsed["timestamp"], "") + self.assertEqual(parsed["logger"], "") + self.assertEqual(parsed["message"], "random text without timestamp") + + def test_parse_normalizes_tabs(self): + """Tabs are normalised to four spaces in raw and message.""" + parsed = parse_line( + "2024-01-01 10:00:00,123 - test - INFO - col1\tcol2\n" + ) + + self.assertNotIn("\t", parsed["raw"]) + self.assertNotIn("\t", parsed["message"]) + self.assertIn("col1 col2", parsed["message"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_log_tailer.py b/tests/test_log_tailer.py index e423c55..8d4a40c 100644 --- a/tests/test_log_tailer.py +++ b/tests/test_log_tailer.py @@ -1,5 +1,4 @@ -""" -Tests for LogTailer class. +"""Tests for LogTailer class. """ import os @@ -166,7 +165,8 @@ def test_double_start(self): def test_parse_simple_serial_log_line(self): """Serial-style lines without explicit logger/level - should still parse.""" + should still parse. + """ tailer = LogTailer( str(self.log_file), self._callback, poll_interval=0.1 ) @@ -184,7 +184,8 @@ def test_parse_simple_serial_log_line(self): def test_parse_line_normalizes_tabs(self): """Tab characters should be normalized to spaces - to avoid visual jumps.""" + to avoid visual jumps. + """ tailer = LogTailer( str(self.log_file), self._callback, poll_interval=0.1 ) @@ -214,9 +215,88 @@ def test_parse_serial_io_arrow_line(self): self.assertEqual(parsed_in["logger"], "serial.log") self.assertEqual(parsed_in["message"], "<<< ok") + def test_detects_truncation_as_rotation(self): + """Copy-truncate rotation (same inode, smaller file) is detected. + + Exercises _check_rotation() directly without starting the + background thread, so the poll loop cannot reopen the file and + reset the read position out from under the assertions. + """ + self.log_file.write_text( + "2024-01-01 10:00:00,000 - test - INFO - one\n" + "2024-01-01 10:00:01,000 - test - INFO - two\n" + ) + + tailer = LogTailer( + str(self.log_file), self._callback, poll_interval=0.05 + ) + + # Open the file and seek to the end, mirroring what start() does, + # but leave the background thread stopped. + tailer._file = open( # noqa: SIM115 + str(self.log_file), encoding="utf-8", errors="replace" + ) + self.addCleanup(tailer._file.close) + tailer._file_inode = os.fstat(tailer._file.fileno()).st_ino + tailer._file.seek(0, 2) # SEEK_END + + # Same inode, no shrink yet -> not a rotation. + self.assertFalse(tailer._check_rotation()) + + # Shrink the file below the read position -> copy-truncate. + self.log_file.write_text("") + self.assertTrue(tailer._check_rotation()) + + def test_picks_up_lines_after_truncation(self): + """After a copy-truncate the running tailer resumes reading.""" + self.log_file.write_text( + "2024-01-01 10:00:00,000 - test - INFO - one\n" + "2024-01-01 10:00:01,000 - test - INFO - two\n" + ) + + tailer = LogTailer( + str(self.log_file), self._callback, poll_interval=0.05 + ) + self.assertTrue(tailer.start()) + + try: + self.log_file.write_text("") + + # After truncation the tailer must pick up new lines again. + with self.log_file.open("a") as handle: + handle.write("2024-01-01 10:00:02,000 - test - INFO - fresh\n") + + deadline = time.time() + 3.0 + while time.time() < deadline and not self.received_lines: + time.sleep(0.05) + + messages = [line["message"] for line in self.received_lines] + self.assertIn("fresh", messages) + finally: + tailer.stop() + + def test_get_last_n_lines_large_file(self): + """Backward block reads return the correct tail of a large file.""" + with self.log_file.open("w") as handle: + for i in range(5000): + handle.write( + f"2024-01-01 10:00:00,000 - test - INFO - line {i}\n" + ) + + tailer = LogTailer( + str(self.log_file), self._callback, poll_interval=0.1 + ) + + last_lines = tailer.get_last_n_lines(3) + + self.assertEqual(len(last_lines), 3) + self.assertEqual(last_lines[-1]["message"], "line 4999") + self.assertEqual(last_lines[0]["message"], "line 4997") + def test_parse_compact_warning_line(self): """Compact OctoPrint warning lines should still - map to WARNING level.""" + map to WARNING level. + """ tailer = LogTailer( str(self.log_file), self._callback, poll_interval=0.1 ) diff --git a/tests/test_plugin_core.py b/tests/test_plugin_core.py index e60ddb0..d50155f 100644 --- a/tests/test_plugin_core.py +++ b/tests/test_plugin_core.py @@ -1,5 +1,4 @@ -""" -Unit tests for core plugin behaviors in octoprint_logmonitor.__init__. +"""Unit tests for core plugin behaviors in octoprint_logmonitor.__init__. These tests run without a real OctoPrint environment by stubbing the required OctoPrint plugin mixins. @@ -32,14 +31,16 @@ def _install_fake_octoprint(): # pylint: disable=too-few-public-methods class DummyBlueprintPlugin: """Minimal BlueprintPlugin stand-in providing - a no-op route decorator.""" + a no-op route decorator. + """ @staticmethod def route( _rule, methods=None, **_kwargs ): # pylint: disable=unused-argument """No-op route decorator that returns - the view function unchanged.""" + the view function unchanged. + """ def decorator(func): return func @@ -87,7 +88,8 @@ def get(self, keys): def getBaseFolder(self, _name): # pylint: disable=invalid-name """Return the configured base folder - (OctoPrint-style camelCase API).""" + (OctoPrint-style camelCase API). + """ return self._base_dir def get_all_data(self): @@ -154,7 +156,8 @@ def has_been_customized(): class OctoPrintAccessPatchedTestCase(unittest.TestCase): """Base test case that patches OctoPrint globals - used by route decorators.""" + used by route decorators. + """ def setUp(self): super().setUp() @@ -975,6 +978,25 @@ def test_start_multi_stream_success(self): self.assertEqual(payload["status"], "multi_started") self.assertEqual(set(payload["started"]), {"a.log", "b.log"}) + def test_start_multi_stream_ensures_flush_timer(self): + (Path(self.temp_dir) / "a.log").write_text("a") + + tailer = MagicMock() + tailer.start.return_value = True + + with ( + patch("octoprint_logmonitor.LogTailer", return_value=tailer), + patch.object(self.plugin, "_ensure_flush_timer") as ensure, + self.app.test_request_context( + "/stream/multi/start", + method="POST", + json={"files": ["a.log"]}, + ), + ): + self.plugin.start_multi_stream() + + ensure.assert_called_once() + def test_stop_multi_stream_stop_all(self): self.plugin._active_tailers = { "a.log": MagicMock(), @@ -989,6 +1011,7 @@ def test_stop_multi_stream_stop_all(self): payload = self._resp(response).get_json() self.assertEqual(payload["status"], "all_stopped") + self.assertEqual(payload["total_stopped"], 2) self.assertEqual(len(self.plugin._active_tailers), 0) def test_on_shutdown_stops_tailers(self): diff --git a/translations/de/LC_MESSAGES/messages.mo b/translations/de/LC_MESSAGES/messages.mo index 438fa0c7c8ebceb99d823181258cdad7006a5914..b2feea927c049bc332c0f1c78e471f28910811d0 100644 GIT binary patch delta 1968 zcmZ|PeMnt(9LMpmdYz^=AM$Q$wH>WC4WH)R#x~1zjuthhXqvQ&J3ZZd>+YU7_lh$H zmqxB)^oO}YLByiS7{##5{s>~wA3cJsu~D$BF^Tezplxh_6g|B^?!YAIqWATCIOq5K ze!u7Z?#CVTotYmiLdT5HKK}3EzcEj}o1cyqW~FrRLkD-`225fl9>;P#g*EsER^S2_ z<8@qvIR$35=-@8w#y+!*9ih?0zz>*@#f4@iSdO>i8hjKRQS*ne3||g>1GmyYf!pyX z)cwvaW~;CX>#zqEKok|wD_F$-_Wn}CEQ>3dIE`9h4%_hpDx=b(8v)cINm)IrGA*b~ zJ8>I69LyiaYWlC@oj4QpKSL#O5nI{cF4NGBwX8xBY%hjz6m?@9iNRh%m3j(QnRif? zn?(h9F_^y^7$S?!jITn9V!Ki658^I-5;Gc@p`pxAq9Qwu%J2-bmVJxLbRqC6Dv(^F zplOw;0BW%t+tI^uyS>rl_S1*>op^$g!aMSKc%42?D#XRr@*Ia5#I0BXUH zP>*5}3EF-`VzGZvN4AV8bShG)M>2s-*%9o*+l3> zqqBjRkbCV4>RA@BieA<*GGx7|0HUZ0?MK}|hRSpj7047Sk#nfbFCfP>td2Gb*QSVG4XG}jlVN~X=csK4umHru20*8b7H?focEEeee zU!kE$f5(2zXEkLyj9M@ncn}r96e`fyQ6)c#ypQ%NDv@uH*T62LuFE5e9<0Gb_!R2C z1zgGgc1;b;;|Q?N{g^C$!@4G8EF}m4%J&m5L4Py z76d*NfeZxFMSPHojDjc($|wQ}EGX?kD(e5`frgp$+xwh-&R%Psz2|MkaG7s1)^)}B zH1b=@Z#G!H|DW+tvqf~D;bMG;G58&m(G_MEi)k2%1(=HExE!0X27OqMk1-dM7ntz~ zpViQa;>0#wh>f@l+vW$@2u9N%b9{{(=ucrOE)O?Lz$VPVPSnKxs6d9%gA=HErmzTS zF_!r)+x;&RD?@^_YE;IxsEqcY7Y{qvuVWJZL0pETPX9eB&^gSBI3Gr!%Sp_1N0Rp0@tL{CwropY{75sk*B;(E+SlCT!k1V^z3PdfckROU}mflVM^ z`^-TJ{y?7^q0~hWjz>+HiPh-EcI-w4_63Q>emaJ6l4LCgIb|u1S*TZ7j7zW=^@?ty z0=$R1&*h>13cy2{8jyiA56hSqR{z5R3LSz#kCg;um|gL2%9h@j>&O9 zYAy96bJ{i3E4YIPa0FTXmf>ShF_&ebwwISf6>i6kcnOusE6l{Nn1cyKy&9`f3AA#c zs@8*AtQSxfeT1555|#NUR6x_HgnYkfXu@ztE8;Dv4C_(bsRPrn5Bb_%4%&9lums(d zORuB~b^lgegF8@b!iV~wxPZiNgSZm!BNg`92O7j+znuYbq+3Bh3l(uID$=946HlWu zeSv!5q~i=Kz;O1aDw>8Y3tNXupb~Yx88=}Up4I-pPeV6U5Tj4h)2y3HIl@PX!*j6GQxO wqr8C?3p-u@k(e-7fj2)ta3iKPC{P$T6YMWf@CUvnTo3VIP2L>{NqOV?3r3Kga{vGU diff --git a/translations/de/LC_MESSAGES/messages.po b/translations/de/LC_MESSAGES/messages.po index 99562e3..9571ced 100644 --- a/translations/de/LC_MESSAGES/messages.po +++ b/translations/de/LC_MESSAGES/messages.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: PROJECT VERSION\n" "Report-Msgid-Bugs-To: i18n@octoprint.org\n" -"POT-Creation-Date: 2026-05-18 10:45+0200\n" +"POT-Creation-Date: 2026-07-05 22:43+0200\n" "PO-Revision-Date: 2026-05-04 21:46+0200\n" "Last-Translator: FULL NAME \n" "Language: de\n" @@ -16,21 +16,21 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Generated-By: Babel 2.18.0\n" +"Generated-By: Babel 2.16.0\n" -#: octoprint_logmonitor/static/js/logmonitor.js:333 +#: octoprint_logmonitor/static/js/logmonitor.js:332 msgid " (switching...)" msgstr " (wird gewechselt...)" -#: octoprint_logmonitor/static/js/logmonitor.js:360 -#, fuzzy, python-format +#: octoprint_logmonitor/static/js/logmonitor.js:359 +#, python-format msgid "%(count)s alert" msgid_plural "%(count)s alerts" msgstr[0] "%(count)s Alarm" msgstr[1] "%(count)s Alarme" -#: octoprint_logmonitor/static/js/logmonitor.js:290 -#, fuzzy, python-format +#: octoprint_logmonitor/static/js/logmonitor.js:289 +#, python-format msgid "%(count)s history entry" msgid_plural "%(count)s history entries" msgstr[0] "%(count)s Verlaufseintrag" @@ -124,7 +124,7 @@ msgstr "Zeigt ein Widget in der Sidebar mit dem Status der Logueberwachung." #: octoprint_logmonitor/templates/logmonitor_tab.jinja2:33 msgid "Download Log" -msgstr "" +msgstr "Protokoll herunterladen" #: octoprint_logmonitor/templates/logmonitor_settings.jinja2:108 msgid "Enable alerts globally" @@ -144,11 +144,11 @@ msgstr "Regex-Suche standardmaessig aktivieren" #: octoprint_logmonitor/templates/logmonitor_tab.jinja2:142 msgid "Export CSV" -msgstr "" +msgstr "CSV exportieren" #: octoprint_logmonitor/templates/logmonitor_tab.jinja2:146 msgid "Export TXT" -msgstr "" +msgstr "TXT exportieren" #: octoprint_logmonitor/templates/logmonitor_tab.jinja2:71 msgid "Filter logs..." @@ -226,7 +226,7 @@ msgstr "Weiter" msgid "No alert history entries yet." msgstr "Noch keine Alarmverlaufseintraege vorhanden." -#: octoprint_logmonitor/static/js/logmonitor.js:366 +#: octoprint_logmonitor/static/js/logmonitor.js:365 msgid "No alerts" msgstr "Keine Alarme" @@ -234,7 +234,7 @@ msgstr "Keine Alarme" msgid "No results found." msgstr "Keine Ergebnisse gefunden." -#: octoprint_logmonitor/static/js/logmonitor.js:337 +#: octoprint_logmonitor/static/js/logmonitor.js:336 msgid "Not streaming" msgstr "Kein Streaming aktiv" @@ -284,6 +284,10 @@ msgstr "Status aktualisieren" msgid "Results per page" msgstr "Ergebnisse pro Seite" +#: octoprint_logmonitor/static/js/logmonitor.js:757 +msgid "Search" +msgstr "Suchen" + #: octoprint_logmonitor/templates/logmonitor_tab.jinja2:10 msgid "Search Logs" msgstr "Protokolle durchsuchen" @@ -300,7 +304,11 @@ msgstr "Suchbegriff..." msgid "Searching logs..." msgstr "Protokolle werden durchsucht..." -#: octoprint_logmonitor/static/js/logmonitor.js:418 +#: octoprint_logmonitor/static/js/logmonitor.js:756 +msgid "Searching..." +msgstr "Wird durchsucht..." + +#: octoprint_logmonitor/static/js/logmonitor.js:417 #: octoprint_logmonitor/templates/logmonitor_settings.jinja2:30 #: octoprint_logmonitor/templates/logmonitor_tab.jinja2:25 #: octoprint_logmonitor/templates/logmonitor_tab.jinja2:94 @@ -384,7 +392,7 @@ msgstr "Ausgeloeste Alarme in einer Verlaufsliste speichern." msgid "Streaming Settings" msgstr "Streaming-Einstellungen" -#: octoprint_logmonitor/static/js/logmonitor.js:331 +#: octoprint_logmonitor/static/js/logmonitor.js:330 msgid "Streaming: " msgstr "Streaming: " diff --git a/translations/messages.pot b/translations/messages.pot index e082a58..abbe578 100644 --- a/translations/messages.pot +++ b/translations/messages.pot @@ -8,27 +8,27 @@ msgid "" msgstr "" "Project-Id-Version: PROJECT VERSION\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2026-05-18 10:45+0200\n" +"POT-Creation-Date: 2026-07-05 22:43+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" -"Generated-By: Babel 2.18.0\n" +"Generated-By: Babel 2.16.0\n" -#: octoprint_logmonitor/static/js/logmonitor.js:333 +#: octoprint_logmonitor/static/js/logmonitor.js:332 msgid " (switching...)" msgstr "" -#: octoprint_logmonitor/static/js/logmonitor.js:360 +#: octoprint_logmonitor/static/js/logmonitor.js:359 #, python-format msgid "%(count)s alert" msgid_plural "%(count)s alerts" msgstr[0] "" msgstr[1] "" -#: octoprint_logmonitor/static/js/logmonitor.js:290 +#: octoprint_logmonitor/static/js/logmonitor.js:289 #, python-format msgid "%(count)s history entry" msgid_plural "%(count)s history entries" @@ -219,7 +219,7 @@ msgstr "" msgid "No alert history entries yet." msgstr "" -#: octoprint_logmonitor/static/js/logmonitor.js:366 +#: octoprint_logmonitor/static/js/logmonitor.js:365 msgid "No alerts" msgstr "" @@ -227,7 +227,7 @@ msgstr "" msgid "No results found." msgstr "" -#: octoprint_logmonitor/static/js/logmonitor.js:337 +#: octoprint_logmonitor/static/js/logmonitor.js:336 msgid "Not streaming" msgstr "" @@ -275,6 +275,10 @@ msgstr "" msgid "Results per page" msgstr "" +#: octoprint_logmonitor/static/js/logmonitor.js:757 +msgid "Search" +msgstr "" + #: octoprint_logmonitor/templates/logmonitor_tab.jinja2:10 msgid "Search Logs" msgstr "" @@ -291,7 +295,11 @@ msgstr "" msgid "Searching logs..." msgstr "" -#: octoprint_logmonitor/static/js/logmonitor.js:418 +#: octoprint_logmonitor/static/js/logmonitor.js:756 +msgid "Searching..." +msgstr "" + +#: octoprint_logmonitor/static/js/logmonitor.js:417 #: octoprint_logmonitor/templates/logmonitor_settings.jinja2:30 #: octoprint_logmonitor/templates/logmonitor_tab.jinja2:25 #: octoprint_logmonitor/templates/logmonitor_tab.jinja2:94 @@ -371,7 +379,7 @@ msgstr "" msgid "Streaming Settings" msgstr "" -#: octoprint_logmonitor/static/js/logmonitor.js:331 +#: octoprint_logmonitor/static/js/logmonitor.js:330 msgid "Streaming: " msgstr "" From 25308cb4ee461fb06dd766a0f50f2ded84feda4e Mon Sep 17 00:00:00 2001 From: Ajimaru Date: Mon, 13 Jul 2026 08:49:29 +0200 Subject: [PATCH 2/2] chore: update CHANGELOG.md to remove unreleased section and previous version details --- CHANGELOG.md | 40 ---------------------------------------- 1 file changed, 40 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 19073a1..d7f9d30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,45 +2,5 @@ All notable changes to this project are documented in this file. -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). For the detailed history of published versions, see the [GitHub releases](https://github.com/Ajimaru/OctoPrint-LogMonitor/releases). - -## [Unreleased] - -### Added - -- Shared `log_parser` module: streaming and searching now classify log - lines identically (search understands serial and compact formats too). -- Copy-truncate log rotation detection: a truncated file no longer stalls - the live stream. -- Documentation: configuration reference, REST API reference, and - troubleshooting guide. - -### Changed - -- Search now streams through log files line by line instead of loading - them fully into memory; the initial-lines read also uses backward block - reads. Memory use no longer scales with file size. -- Hyphenated logger names (e.g. `octoprint.plugins.my-plugin`) parse - correctly. -- `max_alert_history` is now consistently capped at 500 in settings, UI, - and runtime. - -### Fixed - -- Batched line delivery now starts reliably for auto-started and - multi-file streams, and stopping the single-file stream no longer stalls - active multi-file streams. -- The line buffer is hard-capped so memory stays bounded even if flushing - stalls; the search rate limiter prunes idle clients automatically. -- `POST /stream/multi/stop` with `stop_all` reports the actual number of - stopped streams. - -## [0.2.3] - 2026-06 - -- Version 0.2.3: improved log path validation and error handling. - -See [GitHub releases](https://github.com/Ajimaru/OctoPrint-LogMonitor/releases) -for earlier versions.