From bfe6908e2f1a720d9322c7f224662ba2360aa033 Mon Sep 17 00:00:00 2001 From: Ajimaru Date: Wed, 2 Dec 2026 13:05:41 +0100 Subject: [PATCH 1/2] chore: remove unused configuration files for flake8, eslint, and package-lock --- .flake8 | 4 ---- eslint.config.mjs | 39 --------------------------------------- package-lock.json | 6 ------ 3 files changed, 49 deletions(-) delete mode 100644 .flake8 delete mode 100644 eslint.config.mjs delete mode 100644 package-lock.json diff --git a/.flake8 b/.flake8 deleted file mode 100644 index 130aa83..0000000 --- a/.flake8 +++ /dev/null @@ -1,4 +0,0 @@ -[flake8] -max-line-length = 79 -extend-ignore = E203, W503 -exclude = .git,__pycache__,.venv,.venv-*,build,dist diff --git a/eslint.config.mjs b/eslint.config.mjs deleted file mode 100644 index 4f0d281..0000000 --- a/eslint.config.mjs +++ /dev/null @@ -1,39 +0,0 @@ -export default [ - { - files: ["**/*.js"], - languageOptions: { - ecmaVersion: 2022, - sourceType: "script", - globals: { - API_BASEURL: "readonly", - BASEURL: "readonly", - OCTOPRINT_VIEWMODELS: "readonly", - PNotify: "readonly", - $: "readonly", - Audio: "readonly", - Blob: "readonly", - Date: "readonly", - Math: "readonly", - Object: "readonly", - RegExp: "readonly", - alert: "readonly", - confirm: "readonly", - console: "readonly", - document: "readonly", - encodeURIComponent: "readonly", - gettext: "readonly", - isNaN: "readonly", - parseInt: "readonly", - ko: "readonly", - ngettext: "readonly", - setTimeout: "readonly", - clearInterval: "readonly", - setInterval: "readonly", - window: "readonly", - }, - }, - rules: { - "no-unused-vars": "off", - }, - }, -]; diff --git a/package-lock.json b/package-lock.json deleted file mode 100644 index 6bebd26..0000000 --- a/package-lock.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "OctoPrint-LogMonitor", - "lockfileVersion": 3, - "requires": true, - "packages": {} -} From ae61d8bacb870bf98f95d44f3f7f9868c5ce2067 Mon Sep 17 00:00:00 2001 From: Ajimaru Date: Wed, 2 Dec 2026 13:06:13 +0100 Subject: [PATCH 2/2] Refactor templates and improve code formatting - Adjusted HTML templates in logmonitor_settings.jinja2 and logmonitor_tab.jinja2 for better readability and consistency. - Updated indentation and line breaks in various sections to enhance code clarity. - Removed unnecessary settings from pyproject.toml and migrated Ruff configuration to ruff.toml. - Simplified the installation of fake OctoPrint plugins in tests/conftest.py. - Improved test cases for JavaScript extraction and integration API, ensuring better error handling and readability. - Refined log parsing tests to streamline assertions and enhance clarity. - Enhanced test structure in test_log_tailer.py and test_plugin_core.py for better maintainability. - General code cleanup across multiple test files to adhere to PEP 8 standards. --- .codacy.yml | 1 - .djlintrc | 6 + .editorconfig | 5 - .github/workflows/ci.yml | 53 +--- .gitignore | 3 - .isort.cfg | 5 + .pre-commit-config.yaml | 48 ++++ .prettierignore | 12 + .prettierrc.yaml | 12 + README.md | 12 +- octoprint_logmonitor/__init__.py | 257 +++++------------- octoprint_logmonitor/log_searcher.py | 26 +- octoprint_logmonitor/log_tailer.py | 8 +- octoprint_logmonitor/security.py | 20 +- octoprint_logmonitor/static/js/logmonitor.js | 88 +++--- .../templates/logmonitor_settings.jinja2 | 6 +- .../templates/logmonitor_tab.jinja2 | 23 +- pyproject.toml | 18 -- ruff.toml | 28 ++ tests/conftest.py | 24 +- tests/test_i18n_extraction.py | 10 +- tests/test_integration_api.py | 30 +- tests/test_log_parser.py | 12 +- tests/test_log_searcher.py | 12 +- tests/test_log_tailer.py | 68 ++--- tests/test_plugin_core.py | 118 ++------ tests/test_security.py | 3 +- 27 files changed, 345 insertions(+), 563 deletions(-) create mode 100644 .djlintrc create mode 100644 .isort.cfg create mode 100644 .pre-commit-config.yaml create mode 100644 .prettierignore create mode 100644 .prettierrc.yaml create mode 100644 ruff.toml diff --git a/.codacy.yml b/.codacy.yml index 90608b6..788b35b 100644 --- a/.codacy.yml +++ b/.codacy.yml @@ -12,7 +12,6 @@ exclude_paths: - "**/vendor/**" - "**/*.min.js" - "**/*.min.css" - - "eslint.config.mjs" - "**/*.css" # Codacy's server-side Stylelint profile reports broken "scss_*" rules and diff --git a/.djlintrc b/.djlintrc new file mode 100644 index 0000000..84e566f --- /dev/null +++ b/.djlintrc @@ -0,0 +1,6 @@ +{ + "profile": "jinja", + "ignore": "H005,H007,H013,H019,H020,H021,H023,H026,H030,H036,H043,H047,H050,J018,T002", + "max_blank_lines": 1, + "use_gitignore": true +} diff --git a/.editorconfig b/.editorconfig index ad4ec7d..e7be252 100644 --- a/.editorconfig +++ b/.editorconfig @@ -11,11 +11,6 @@ insert_final_newline = true trim_trailing_whitespace = true max_line_length = 90 -# Python stays at 88 (black/isort default) until the linters move to 90 too; -# isort reads this value. -[*.py] -max_line_length = 88 - [*.{yml,yaml,json,less,md}] indent_size = 2 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 347a357..da8550c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,7 +20,7 @@ env: TEST_DEPS: "-e .[develop]" TEST_PATH: "" # "pre-commit" once the repo has a hook config, else "ruff" with RUFF_ARGS. - LINT: ruff + LINT: pre-commit RUFF_ARGS: "" # setup.py imports octoprint_setuptools, so those builds need OctoPrint installed. BUILD_ARGS: "" @@ -36,26 +36,6 @@ jobs: with: python-version: "3.13" - # Hooks with `language: system` need the node packages and ShellCheck 0.11. - - name: Set up Node.js - if: env.LINT == 'pre-commit' && hashFiles('package.json') != '' - uses: actions/setup-node@v7 - with: - node-version: "22" - - - name: Install node packages - if: env.LINT == 'pre-commit' && hashFiles('package.json') != '' - run: | - if [ -f package-lock.json ]; then npm ci --no-audit --no-fund - else npm install --no-audit --no-fund; fi - - - name: Install ShellCheck - if: env.LINT == 'pre-commit' && hashFiles('.githooks/shellcheck-hook.sh') != '' - run: | - url=https://github.com/koalaman/shellcheck/releases/download/v0.11.0/shellcheck-v0.11.0.linux.x86_64.tar.xz - curl -fsSL "$url" | tar -xJ -C "$RUNNER_TEMP" - sudo install "$RUNNER_TEMP/shellcheck-v0.11.0/shellcheck" /usr/local/bin/shellcheck - - name: Cache pre-commit hook environments if: env.LINT == 'pre-commit' uses: actions/cache@v6 @@ -65,9 +45,6 @@ jobs: - name: Run pre-commit if: env.LINT == 'pre-commit' - # The translations hook needs a local venv; the Translations job covers it. - env: - SKIP: check-translations run: | python -m pip install pre-commit pre-commit run --all-files --show-diff-on-failure @@ -88,18 +65,18 @@ jobs: matrix: include: # Every Python version each OctoPrint generation supports. - - { octoprint: "1.x", python: "3.9", runner: ubuntu-24.04 } - - { octoprint: "1.x", python: "3.10", runner: ubuntu-latest } - - { octoprint: "1.x", python: "3.11", runner: ubuntu-latest } - - { octoprint: "1.x", python: "3.12", runner: ubuntu-latest } - - { octoprint: "1.x", python: "3.13", runner: ubuntu-latest } - - { octoprint: "2.x", python: "3.9", runner: ubuntu-24.04 } - - { octoprint: "2.x", python: "3.10", runner: ubuntu-latest } - - { octoprint: "2.x", python: "3.11", runner: ubuntu-latest } - - { octoprint: "2.x", python: "3.12", runner: ubuntu-latest } - - { octoprint: "2.x", python: "3.13", runner: ubuntu-latest, coverage: true } - - { octoprint: "2.x", python: "3.14", runner: ubuntu-latest } - - { octoprint: "2.x", python: "3.15", runner: ubuntu-latest } + - {octoprint: "1.x", python: "3.9", runner: ubuntu-24.04} + - {octoprint: "1.x", python: "3.10", runner: ubuntu-latest} + - {octoprint: "1.x", python: "3.11", runner: ubuntu-latest} + - {octoprint: "1.x", python: "3.12", runner: ubuntu-latest} + - {octoprint: "1.x", python: "3.13", runner: ubuntu-latest} + - {octoprint: "2.x", python: "3.9", runner: ubuntu-24.04} + - {octoprint: "2.x", python: "3.10", runner: ubuntu-latest} + - {octoprint: "2.x", python: "3.11", runner: ubuntu-latest} + - {octoprint: "2.x", python: "3.12", runner: ubuntu-latest} + - {octoprint: "2.x", python: "3.13", runner: ubuntu-latest, coverage: true} + - {octoprint: "2.x", python: "3.14", runner: ubuntu-latest} + - {octoprint: "2.x", python: "3.15", runner: ubuntu-latest} env: CODACY_API_TOKEN: ${{ secrets.CODACY_API_TOKEN }} steps: @@ -159,8 +136,8 @@ jobs: fail-fast: false matrix: include: - - { octoprint: "1.x", python: "3.9", runner: ubuntu-24.04, disabled: false } - - { octoprint: "2.x", python: "3.13", runner: ubuntu-latest, disabled: false } + - {octoprint: "1.x", python: "3.9", runner: ubuntu-24.04, disabled: false} + - {octoprint: "2.x", python: "3.13", runner: ubuntu-latest, disabled: false} steps: - uses: actions/checkout@v7 diff --git a/.gitignore b/.gitignore index 36acab1..ea328d3 100644 --- a/.gitignore +++ b/.gitignore @@ -41,11 +41,8 @@ Thumbs.db .venv/ venv/ env/ -.logs/ .coverage .cache/ -.githooks/ -.pre-commit-config.yaml .octoprint-*/ # Local-only lint config diff --git a/.isort.cfg b/.isort.cfg new file mode 100644 index 0000000..b4a0b9c --- /dev/null +++ b/.isort.cfg @@ -0,0 +1,5 @@ +# Import order shared by all plugin repos; compatible with ruff format. +[settings] +profile = black +line_length = 90 +extend_skip_glob = **/vendor/*,3rdPartySoftware/*,archive/* diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..4a4cbd3 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,48 @@ +# Same hooks in every plugin repo, following OctoPrint core's setup. +# Set up once with `pre-commit install`; CI runs them on every push. +exclude: (^|/)(translations|vendor)/|^(docs|scripts|archive|3rdPartySoftware)/|\.(css|svg|map|gcode)$|\.min\.js$ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v6.0.0 + hooks: + - id: end-of-file-fixer + - id: trailing-whitespace + - id: check-case-conflict + - id: check-json + - id: check-yaml + # mkdocs.yml uses custom tags; only the syntax is checked. + args: [--unsafe] + - id: check-toml + - id: check-merge-conflict + - repo: https://github.com/PyCQA/isort + rev: 9.0.2 + hooks: + - id: isort + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.17.6 + hooks: + - id: ruff-check + args: [--fix] + - id: ruff-format + - repo: https://github.com/djlint/djlint + rev: v1.54.2 + hooks: + - id: djlint-reformat-jinja + - id: djlint-jinja + - repo: https://github.com/rbubley/mirrors-prettier + rev: v3.10.1 + hooks: + - id: prettier + files: \.(js|json|less|ya?ml)$ + - repo: https://github.com/codespell-project/codespell + rev: v2.4.3 + hooks: + - id: codespell + # Identifiers, config keys and product names, not typos. + args: + - --ignore-words-list + - commitish,offsetp,colorfull,basf,paht,sme,unparseable,pre-selected + - repo: https://github.com/shellcheck-py/shellcheck-py + rev: v0.11.0.1-1 + hooks: + - id: shellcheck diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..5b11dbf --- /dev/null +++ b/.prettierignore @@ -0,0 +1,12 @@ +# Same scope as the prettier hook in .pre-commit-config.yaml. +*.md +*.css +*.min.js +**/package.json +**/package-lock.json +**/translations/ +**/vendor/ +docs/ +scripts/ +archive/ +3rdPartySoftware/ diff --git a/.prettierrc.yaml b/.prettierrc.yaml new file mode 100644 index 0000000..b677871 --- /dev/null +++ b/.prettierrc.yaml @@ -0,0 +1,12 @@ +# Prettier settings shared by all plugin repos, taken from OctoPrint core. +printWidth: 90 +tabWidth: 4 +semi: true +trailingComma: "none" +singleQuote: false +quoteProps: consistent +bracketSpacing: false +overrides: + - files: ["*.yaml", "*.yml", "*.json", "*.less"] + options: + tabWidth: 2 diff --git a/README.md b/README.md index e2a15ff..61ac561 100644 --- a/README.md +++ b/README.md @@ -145,14 +145,14 @@ When a log entry matches configured trigger severities (default: WARNING/ERROR/C 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] +python -m pip install -e .[develop] pre-commit +pre-commit install # Run the test suite python -m pytest -# Lint / format -python -m flake8 octoprint_logmonitor tests -python -m black octoprint_logmonitor tests +# Lint / format (the same hooks CI runs) +pre-commit run --all-files ``` The plugin API used by the frontend is documented in the [REST API reference](https://ajimaru.github.io/OctoPrint-LogMonitor/rest-api/). @@ -194,14 +194,12 @@ Summary: this project exposes many status and quality badges (CI, linting, cover ### ๐Ÿงช 2. Code Quality & Formatting -[![Code style: black](https://img.shields.io/badge/code%20style-black-000000?style=flat-square&logo=black&logoColor=white)](https://github.com/psf/black) +[![Code style: Ruff](https://img.shields.io/badge/code%20style-ruff-261230?style=flat-square&logo=ruff&logoColor=D7FF64)](https://github.com/astral-sh/ruff) [![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat-square&labelColor=ef8336&logo=python&logoColor=white)](https://pycqa.github.io/isort/) [![Code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4?style=flat-square&logo=prettier&logoColor=white)](https://github.com/prettier/prettier) [![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?style=flat-square&logo=pre-commit&logoColor=white)](https://pre-commit.com/) [![Codacy Badge](https://img.shields.io/codacy/grade/1b946ed41ef2479fa1eb254e6eea9fb0?style=flat-square&logo=codacy&logoColor=white)](https://app.codacy.com/gh/Ajimaru/OctoPrint-LogMonitor/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade) [![Coverage](https://img.shields.io/codecov/c/github/Ajimaru/OctoPrint-LogMonitor?style=flat-square&logo=codecov&logoColor=white)](https://codecov.io/gh/Ajimaru/OctoPrint-LogMonitor) -[![Pylint Score](https://img.shields.io/badge/pylint-10.0-green?style=flat-square&logo=python&logoColor=white)](https://www.pylint.org/) -[![Bandit Security](https://img.shields.io/badge/bandit-security-green?style=flat-square&logo=python&logoColor=white)](https://bandit.readthedocs.io/en/latest/) [![Depfu](https://badges.depfu.com/badges/b1bd984976a5ccb7ac298737eabe686f/status.svg)](https://depfu.com) [![Known Vulnerabilities](https://snyk.io/test/github/Ajimaru/OctoPrint-LogMonitor/badge.svg)](https://snyk.io/test/github/Ajimaru/OctoPrint-LogMonitor) diff --git a/octoprint_logmonitor/__init__.py b/octoprint_logmonitor/__init__.py index 9cc4f2c..e7858af 100644 --- a/octoprint_logmonitor/__init__.py +++ b/octoprint_logmonitor/__init__.py @@ -171,9 +171,7 @@ def on_after_startup(self): else: self._logger.warning("Failed to auto-start streaming") else: - self._logger.warning( - f"Default log file not found: {filepath}" - ) + self._logger.warning(f"Default log file not found: {filepath}") except Exception as e: self._logger.error(f"Error auto-starting stream: {e}") @@ -196,9 +194,7 @@ def on_shutdown(self): if tailer.is_running(): tailer.stop() except Exception as e: - self._logger.error( - f"Error stopping tailer for {filename}: {e}" - ) + self._logger.error(f"Error stopping tailer for {filename}: {e}") self._active_tailers.clear() self._stop_alert_monitoring() @@ -222,23 +218,14 @@ def clamp_int_setting(key, default, minimum, maximum): parsed = default plugin_data[key] = min(maximum, max(minimum, parsed)) - raw_interval_seconds = plugin_data.get( - "stream_poll_interval_s" - ) - raw_interval_ms = plugin_data.get( - "stream_poll_interval_ms" - ) + raw_interval_seconds = plugin_data.get("stream_poll_interval_s") + raw_interval_ms = plugin_data.get("stream_poll_interval_ms") # Backward compatibility: convert legacy milliseconds # setting. - if ( - raw_interval_seconds is None - and raw_interval_ms is not None - ): + if raw_interval_seconds is None and raw_interval_ms is not None: try: - raw_interval_seconds = ( - float(raw_interval_ms) / 1000.0 - ) + raw_interval_seconds = float(raw_interval_ms) / 1000.0 except (TypeError, ValueError): raw_interval_seconds = 5.0 @@ -258,15 +245,11 @@ 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) # Keep in sync with the runtime cap (MAX_HISTORY_LIMIT). - clamp_int_setting( - "max_alert_history", 100, 10, 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): - plugin_data[ - "alerts_enabled" - ] = alerts_enabled.lower() in { + plugin_data["alerts_enabled"] = alerts_enabled.lower() in { "1", "true", "yes", @@ -410,9 +393,7 @@ def _get_available_log_filenames(self): try: 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}" - ) + self._logger.error(f"Error listing log filenames for template vars: {e}") return [] def _get_stream_poll_interval_seconds(self) -> float: @@ -442,9 +423,7 @@ def get_log_files(self): log_dir = self._get_logs_base_folder() if not os.path.exists(log_dir): - return flask.jsonify( - {"files": [], "error": "Log directory not found"} - ) + return flask.jsonify({"files": [], "error": "Log directory not found"}) files = [ { @@ -463,8 +442,7 @@ def get_log_files(self): flask.jsonify( { "files": [], - "error": "Failed to list log files." - " See server log for details.", + "error": "Failed to list log files. See server log for details.", } ), 500, @@ -483,9 +461,7 @@ def search_logs(self): f"Search rate limit exceeded for {client_ip}", ) return ( - flask.jsonify( - {"error": "Too many requests. Please slow down."} - ), + flask.jsonify({"error": "Too many requests. Please slow down."}), 429, ) @@ -496,12 +472,9 @@ def search_logs(self): query = flask.request.args.get("query", "") raw_levels = flask.request.args.getlist("levels") case_sensitive = ( - flask.request.args.get("case_sensitive", "false").lower() - == "true" - ) - use_regex = ( - flask.request.args.get("use_regex", "false").lower() == "true" + flask.request.args.get("case_sensitive", "false").lower() == "true" ) + use_regex = flask.request.args.get("use_regex", "false").lower() == "true" # Validate and clamp offset / limit try: @@ -513,9 +486,7 @@ def search_logs(self): limit = int(flask.request.args.get("limit", default_limit)) except (ValueError, TypeError): return ( - flask.jsonify( - {"error": "offset and limit must be integers"} - ), + flask.jsonify({"error": "offset and limit must be integers"}), 400, ) @@ -530,8 +501,7 @@ def search_logs(self): flask.jsonify( { "error": ( - "Invalid severity level(s): " - f"{', '.join(invalid_levels)}" + f"Invalid severity level(s): {', '.join(invalid_levels)}" ) } ), @@ -548,13 +518,9 @@ def search_logs(self): # --- File-size guard --- if not check_file_size(filepath): - self._logger.warning( - f"Search rejected: file too large: {filename}" - ) + self._logger.warning(f"Search rejected: file too large: {filename}") return ( - flask.jsonify( - {"error": "Log file is too large to process"} - ), + flask.jsonify({"error": "Log file is too large to process"}), 413, ) @@ -577,9 +543,7 @@ def search_logs(self): except Exception as e: self._logger.error(f"Error searching logs: {e}") return ( - flask.jsonify( - {"error": "Search failed. See server log for details."} - ), + flask.jsonify({"error": "Search failed. See server log for details."}), 500, ) @@ -589,14 +553,10 @@ def start_stream(self): """Start or switch log streaming.""" try: data = flask.request.get_json(silent=True) or {} - filename = data.get( - "file", self._settings.get(["default_log_file"]) - ) + filename = data.get("file", self._settings.get(["default_log_file"])) # --- Filename / path validation --- - filepath, err_code = self._resolve_log_path( - filename, "stream/start" - ) + filepath, err_code = self._resolve_log_path(filename, "stream/start") if filepath is None: if err_code is None: return flask.jsonify({"error": "internal error"}), 500 @@ -605,13 +565,9 @@ def start_stream(self): # --- File-size guard --- if not check_file_size(filepath): - self._logger.warning( - f"Stream rejected: file too large: {filename}" - ) + self._logger.warning(f"Stream rejected: file too large: {filename}") return ( - flask.jsonify( - {"error": "Log file is too large to stream"} - ), + flask.jsonify({"error": "Log file is too large to stream"}), 413, ) @@ -639,9 +595,7 @@ def start_stream(self): # Send initial lines initial_lines_count = 100 # Default - initial_lines = self._tailer.get_last_n_lines( - initial_lines_count - ) + initial_lines = self._tailer.get_last_n_lines(initial_lines_count) return flask.jsonify( { @@ -660,10 +614,7 @@ def start_stream(self): self._logger.error(f"Error starting stream: {e}") return ( flask.jsonify( - { - "error": "Failed to start streaming." - " See server log for details." - } + {"error": "Failed to start streaming. See server log for details."} ), 500, ) @@ -693,9 +644,7 @@ def stop_stream(self): self._logger.error(f"Error stopping stream: {e}") return flask.jsonify({"error": "Failed to stop stream"}), 500 - @octoprint.plugin.BlueprintPlugin.route( - "/stream/multi/start", methods=["POST"] - ) + @octoprint.plugin.BlueprintPlugin.route("/stream/multi/start", methods=["POST"]) @no_firstrun_access def start_multi_stream(self): """Start streaming multiple log files simultaneously.""" @@ -709,9 +658,7 @@ def start_multi_stream(self): # Hard cap: prevent absurdly large file lists if len(files) > 20: return ( - flask.jsonify( - {"error": "Too many files specified (max 20)"} - ), + flask.jsonify({"error": "Too many files specified (max 20)"}), 400, ) @@ -720,18 +667,12 @@ def start_multi_stream(self): for filename in files: # Validate filename and path - filepath, err_code = self._resolve_log_path( - filename, "multi-stream" - ) + filepath, err_code = self._resolve_log_path(filename, "multi-stream") if filepath is None: if err_code is None: return flask.jsonify({"error": "internal error"}), 500 msg = _LOG_PATH_ERRORS[err_code][0] - label = ( - filename - if isinstance(filename, str) - else str(filename) - ) + label = filename if isinstance(filename, str) else str(filename) failed_files.append({"file": label, "error": msg}) continue @@ -779,9 +720,7 @@ def callback(line): self._active_tailers[filename] = tailer started_files.append(filename) else: - failed_files.append( - {"file": filename, "error": "Failed to start"} - ) + failed_files.append({"file": filename, "error": "Failed to start"}) if started_files: self._ensure_flush_timer() @@ -802,9 +741,7 @@ def callback(line): 500, ) - @octoprint.plugin.BlueprintPlugin.route( - "/stream/multi/stop", methods=["POST"] - ) + @octoprint.plugin.BlueprintPlugin.route("/stream/multi/stop", methods=["POST"]) @no_firstrun_access def stop_multi_stream(self): """Stop streaming specific log files.""" @@ -835,9 +772,7 @@ def stop_multi_stream(self): stopped_files = [] for filename in files: # Only allow plain string filenames; ignore others silently - if not isinstance(filename, str) or not validate_filename( - filename - ): + if not isinstance(filename, str) or not validate_filename(filename): continue if filename in self._active_tailers: try: @@ -845,9 +780,7 @@ def stop_multi_stream(self): del self._active_tailers[filename] stopped_files.append(filename) except Exception as e: - self._logger.error( - f"Error stopping {filename}: {e}" - ) + self._logger.error(f"Error stopping {filename}: {e}") self._stop_flush_timer_if_idle() return flask.jsonify( @@ -876,9 +809,7 @@ def reset_alerts(self): self._logger.error(f"Error resetting alerts: {e}") return flask.jsonify({"error": "Failed to reset alerts"}), 500 - @octoprint.plugin.BlueprintPlugin.route( - "/debug/frontend", methods=["POST"] - ) + @octoprint.plugin.BlueprintPlugin.route("/debug/frontend", methods=["POST"]) @no_firstrun_access def frontend_debug_log(self): """Write frontend debug events into OctoPrint server logs.""" @@ -899,9 +830,7 @@ def frontend_debug_log(self): payload_text = "" if payload is not None: try: - payload_text = json.dumps( - payload, ensure_ascii=True, default=str - ) + payload_text = json.dumps(payload, ensure_ascii=True, default=str) except TypeError: payload_text = str(payload) payload_text = payload_text[:2000] @@ -913,9 +842,7 @@ def frontend_debug_log(self): f" | ip={client_ip} | payload={payload_text}" ) else: - self._logger.debug( - f"[Frontend Debug] {message} | ip={client_ip}" - ) + self._logger.debug(f"[Frontend Debug] {message} | ip={client_ip}") return flask.jsonify({"status": "logged"}) @@ -923,9 +850,7 @@ def frontend_debug_log(self): self._logger.error(f"Error writing frontend debug log: {e}") return flask.jsonify({"error": "Failed to write debug log"}), 500 - @octoprint.plugin.BlueprintPlugin.route( - "/debug/test-entries", methods=["POST"] - ) + @octoprint.plugin.BlueprintPlugin.route("/debug/test-entries", methods=["POST"]) @no_firstrun_access def write_debug_test_entries(self): """Write one test entry per severity category into OctoPrint logs.""" @@ -988,10 +913,7 @@ def export_results(self): format_type = data.get("format", "csv").lower() # Guard against excessively large export payloads - if ( - not isinstance(results, list) - or len(results) > MAX_SEARCH_LIMIT - ): + if not isinstance(results, list) or len(results) > MAX_SEARCH_LIMIT: return ( flask.jsonify( { @@ -1022,18 +944,14 @@ def export_results(self): return flask.Response( content, mimetype=mimetype, - headers={ - "Content-Disposition": (f"attachment;filename={filename}") - }, + headers={"Content-Disposition": (f"attachment;filename={filename}")}, ) except Exception as e: self._logger.error(f"Error exporting results: {e}") return flask.jsonify({"error": "Export failed"}), 500 - @octoprint.plugin.BlueprintPlugin.route( - "/download/", methods=["GET"] - ) + @octoprint.plugin.BlueprintPlugin.route("/download/", methods=["GET"]) @no_firstrun_access def download_log_file(self, filename): """Download a log file directly.""" @@ -1065,8 +983,7 @@ def download_log_file(self, filename): flask.jsonify( { "error": ( - f"File is too large to download " - f"(limit {size_mb} MiB)" + f"File is too large to download (limit {size_mb} MiB)" ) } ), @@ -1124,9 +1041,7 @@ def get_alert_history(self): 500, ) - @octoprint.plugin.BlueprintPlugin.route( - "/alert-history/clear", methods=["POST"] - ) + @octoprint.plugin.BlueprintPlugin.route("/alert-history/clear", methods=["POST"]) @no_firstrun_access def clear_alert_history(self): """Clear alert history.""" @@ -1143,9 +1058,7 @@ def clear_alert_history(self): 500, ) - @octoprint.plugin.BlueprintPlugin.route( - "/alerts/monitor/status", methods=["GET"] - ) + @octoprint.plugin.BlueprintPlugin.route("/alerts/monitor/status", methods=["GET"]) @no_firstrun_access def get_alert_monitor_status(self): """Return current alert-monitor configuration and active files.""" @@ -1163,9 +1076,7 @@ def get_alert_monitor_status(self): except Exception as e: self._logger.error(f"Error getting alert monitor status: {e}") return ( - flask.jsonify( - {"error": "Failed to retrieve alert monitor status"} - ), + flask.jsonify({"error": "Failed to retrieve alert monitor status"}), 500, ) @@ -1219,9 +1130,7 @@ def _get_logs_base_folder(self) -> str: if isinstance(candidate, str) and candidate: candidates.append(candidate) except Exception as e: - self._logger.debug( - "global_get_basefolder('logs') lookup failed: %s", e - ) + self._logger.debug("global_get_basefolder('logs') lookup failed: %s", e) base_folder_getter = getattr(self._settings, "getBaseFolder", None) if callable(base_folder_getter): @@ -1242,13 +1151,9 @@ def _get_logs_base_folder(self) -> str: if isinstance(candidate, str) and candidate: noarg_base_folder = candidate except Exception as e: - self._logger.debug( - "getBaseFolder() fallback failed: %s", e - ) + self._logger.debug("getBaseFolder() fallback failed: %s", e) except Exception as e: - self._logger.debug( - "getBaseFolder('logs') lookup failed: %s", e - ) + self._logger.debug("getBaseFolder('logs') lookup failed: %s", e) try: # pylint: disable=import-outside-toplevel @@ -1262,9 +1167,7 @@ def _get_logs_base_folder(self) -> str: if isinstance(candidate, str) and candidate: candidates.append(candidate) except Exception as e: - self._logger.debug( - "octoprint.settings fallback lookup failed: %s", e - ) + self._logger.debug("octoprint.settings fallback lookup failed: %s", e) for candidate in candidates: if os.path.isdir(candidate): @@ -1276,8 +1179,7 @@ def _get_logs_base_folder(self) -> str: if noarg_base_folder: self._logger.debug( - "Skipping no-arg getBaseFolder() result" - " for log resolution: %s", + "Skipping no-arg getBaseFolder() result for log resolution: %s", noarg_base_folder, ) @@ -1333,17 +1235,10 @@ def _write_unknown_debug_test_log(self, message: str) -> None: log_dir = self._get_logs_base_folder() filepath = os.path.join(log_dir, "octoprint.log") timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S,%f")[:-3] - with open( - filepath, "a", encoding="utf-8", errors="replace" - ) as handle: - handle.write( - f"{timestamp} - {self._logger.name}" - f" - UNKNOWN - {message}\n" - ) + with open(filepath, "a", encoding="utf-8", errors="replace") as handle: + handle.write(f"{timestamp} - {self._logger.name} - UNKNOWN - {message}\n") except OSError as e: - self._logger.error( - f"Failed to write UNKNOWN debug test log entry: {e}" - ) + self._logger.error(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.""" @@ -1357,9 +1252,7 @@ def _start_flush_timer(self): 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 = threading.Timer(interval, self._flush_line_buffer) self._flush_timer.daemon = True self._flush_timer.start() @@ -1419,9 +1312,7 @@ def _flush_line_buffer(self): def _get_alert_monitor_files(self): """Resolve list of log files that should drive severity alerts.""" log_dir = self._get_logs_base_folder() - mode = ( - self._settings.get(["alerts_monitor_mode"]) or "selected" - ).lower() + mode = (self._settings.get(["alerts_monitor_mode"]) or "selected").lower() if mode == "all": configured = self._get_available_log_filenames() @@ -1486,13 +1377,9 @@ def _refresh_runtime_alert_settings(self): settings_snapshot = { "alerts_enabled": bool(self._settings.get(["alerts_enabled"])), "severity_triggers": normalized_triggers, - "alert_history_enabled": bool( - self._settings.get(["alert_history_enabled"]) - ), + "alert_history_enabled": bool(self._settings.get(["alert_history_enabled"])), "max_alert_history": max_alert_history, - "enable_notifications": bool( - self._settings.get(["enable_notifications"]) - ), + "enable_notifications": bool(self._settings.get(["enable_notifications"])), } with self._runtime_settings_lock: @@ -1575,9 +1462,7 @@ def _stop_alert_monitoring(self): if tailer.is_running(): tailer.stop() except Exception as e: - self._logger.error( - f"Error stopping alert monitor for {filename}: {e}" - ) + self._logger.error(f"Error stopping alert monitor for {filename}: {e}") self._alert_tailers.clear() def _restart_alert_monitoring(self): @@ -1585,16 +1470,12 @@ def _restart_alert_monitoring(self): self._stop_alert_monitoring() if not self._settings.get(["alerts_enabled"]): - self._logger.info( - "Alert monitor disabled: alerts are globally disabled" - ) + self._logger.info("Alert monitor disabled: alerts are globally disabled") return files = self._get_alert_monitor_files() if not files: - self._logger.info( - "Alert monitor disabled: no valid log files configured" - ) + self._logger.info("Alert monitor disabled: no valid log files configured") return log_dir = self._get_logs_base_folder() @@ -1619,9 +1500,7 @@ def callback(line): if tailer.start(): self._alert_tailers[filename] = tailer else: - self._logger.warning( - f"Failed to start alert monitor for {filename}" - ) + self._logger.warning(f"Failed to start alert monitor for {filename}") self._logger.info( f"Alert monitor active for {len(self._alert_tailers)} log file(s)" @@ -1642,9 +1521,7 @@ def _record_alert_line(self, parsed_line, force=False): return with self._alert_lock: - self._alert_counts[level] = ( - self._alert_counts.get(level, 0) + 1 - ) + self._alert_counts[level] = self._alert_counts.get(level, 0) + 1 if runtime_settings["alert_history_enabled"]: alert_entry = { @@ -1658,9 +1535,7 @@ def _record_alert_line(self, parsed_line, force=False): max_history = runtime_settings["max_alert_history"] if len(self._alert_history) > max_history: - self._alert_history = self._alert_history[ - -max_history: - ] + self._alert_history = self._alert_history[-max_history:] self._plugin_manager.send_plugin_message( self._identifier, @@ -1669,9 +1544,7 @@ def _record_alert_line(self, parsed_line, force=False): "level": level, "count": self._alert_counts[level], "message": parsed_line.get("message", ""), - "notification_enabled": runtime_settings[ - "enable_notifications" - ], + "notification_enabled": runtime_settings["enable_notifications"], "source_file": parsed_line.get("_source_file", ""), }, ) @@ -1702,9 +1575,7 @@ def _handle_log_line(self, parsed_line): # Optionally mask sensitive data before sending to frontend if self._settings.get(["mask_log_content"]): masked = dict(parsed_line) - masked["message"] = mask_sensitive_data( - masked.get("message", "") - ) + masked["message"] = mask_sensitive_data(masked.get("message", "")) masked["raw"] = mask_sensitive_data(masked.get("raw", "")) send_line = masked else: diff --git a/octoprint_logmonitor/log_searcher.py b/octoprint_logmonitor/log_searcher.py index 880d164..5d3f96c 100644 --- a/octoprint_logmonitor/log_searcher.py +++ b/octoprint_logmonitor/log_searcher.py @@ -105,9 +105,7 @@ def search( # Validate and normalize severity levels if levels is not None: allowed_levels: set[str] = { - lvl.upper() - for lvl in levels - if lvl.upper() in self.VALID_LEVELS + lvl.upper() for lvl in levels if lvl.upper() in self.VALID_LEVELS } else: allowed_levels = self.VALID_LEVELS.copy() @@ -117,16 +115,14 @@ def search( if query and len(query) > MAX_QUERY_LENGTH: if self._logger: self._logger.error( - f"Search query rejected: exceeds {MAX_QUERY_LENGTH} " - "characters" + f"Search query rejected: exceeds {MAX_QUERY_LENGTH} characters" ) return { "results": [], "total": 0, "offset": offset, "limit": limit, - "error": f"Query exceeds maximum length of " - f"{MAX_QUERY_LENGTH} characters", + "error": f"Query exceeds maximum length of {MAX_QUERY_LENGTH} characters", } if query: try: @@ -193,13 +189,9 @@ def search( 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 - ] + pending_after = [item for item in pending_after if item[1] > 0] - if self._matches_filters( - parsed, search_pattern, allowed_levels - ): + if self._matches_filters(parsed, search_pattern, allowed_levels): total_matches += 1 # Include this match on the requested page @@ -207,13 +199,9 @@ def search( match_entry = parsed.copy() if context_lines > 0: - match_entry["context_before"] = list( - before_buffer or () - ) + match_entry["context_before"] = list(before_buffer or ()) match_entry["context_after"] = [] - pending_after.append( - [match_entry, context_lines] - ) + pending_after.append([match_entry, context_lines]) results.append(match_entry) diff --git a/octoprint_logmonitor/log_tailer.py b/octoprint_logmonitor/log_tailer.py index cd142a1..f6b8ac9 100644 --- a/octoprint_logmonitor/log_tailer.py +++ b/octoprint_logmonitor/log_tailer.py @@ -89,9 +89,7 @@ def start(self) -> bool: self._running = True if self._logger: - self._logger.info( - f"LogTailer started for {self._filepath}" - ) + self._logger.info(f"LogTailer started for {self._filepath}") return True @@ -125,9 +123,7 @@ def stop(self, timeout: float = 5.0) -> bool: if self._thread.is_alive(): if self._logger: - self._logger.warning( - "LogTailer thread did not stop gracefully" - ) + self._logger.warning("LogTailer thread did not stop gracefully") return False if self._file: diff --git a/octoprint_logmonitor/security.py b/octoprint_logmonitor/security.py index 7f0f6d8..69d8d18 100644 --- a/octoprint_logmonitor/security.py +++ b/octoprint_logmonitor/security.py @@ -121,9 +121,7 @@ def is_safe_path(base_dir: str, filename: str) -> bool: try: abs_base = os.path.realpath(os.path.abspath(base_dir)) # Join base with the user-supplied name and resolve - candidate = os.path.realpath( - os.path.abspath(os.path.join(abs_base, filename)) - ) + candidate = os.path.realpath(os.path.abspath(os.path.join(abs_base, filename))) # Candidate must start with base followed by a separator, OR equal base # itself return candidate == abs_base or candidate.startswith(abs_base + os.sep) @@ -230,12 +228,8 @@ def validate_severity_levels( """ if not levels: return [], [] - valid = [ - lvl.upper() for lvl in levels if lvl.upper() in VALID_SEVERITY_LEVELS - ] - invalid = [ - lvl for lvl in levels if lvl.upper() not in VALID_SEVERITY_LEVELS - ] + valid = [lvl.upper() for lvl in levels if lvl.upper() in VALID_SEVERITY_LEVELS] + invalid = [lvl for lvl in levels if lvl.upper() not in VALID_SEVERITY_LEVELS] return valid, invalid @@ -335,9 +329,7 @@ def cleanup(self) -> None: 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 - ] + remaining = [t for t in self._clients[key] if now - t < self._period] if remaining: self._clients[key] = remaining else: @@ -506,6 +498,4 @@ def search_with_timeout(pattern: Any, text: str) -> bool: return bool(pattern.search(text, timeout=REGEX_TIMEOUT_SECONDS)) except TimeoutError as exc: # regex>=2022 raises the builtin TimeoutError on expiry. - raise PatternTimeoutError( - "Search pattern exceeded its time budget" - ) from exc + raise PatternTimeoutError("Search pattern exceeded its time budget") from exc diff --git a/octoprint_logmonitor/static/js/logmonitor.js b/octoprint_logmonitor/static/js/logmonitor.js index 4a9fbd6..33e5c07 100644 --- a/octoprint_logmonitor/static/js/logmonitor.js +++ b/octoprint_logmonitor/static/js/logmonitor.js @@ -55,7 +55,7 @@ $(() => { self.debugLog = (message, payload) => { if (!self.isDebugMode()) return; - var body = { message: String(message || "") }; + var body = {message: String(message || "")}; if (typeof payload !== "undefined") { body.payload = payload; } @@ -65,7 +65,7 @@ $(() => { method: "POST", data: JSON.stringify(body), contentType: "application/json", - dataType: "json", + dataType: "json" }).fail(() => { // Intentionally silent: never spam browser console for debug logging. }); @@ -76,7 +76,7 @@ $(() => { new PNotify({ title: "Log Monitor", text: "Enable debug mode first.", - type: "notice", + type: "notice" }); return; } @@ -85,7 +85,7 @@ $(() => { url: pluginBaseUrl + "/debug/test-entries", method: "POST", contentType: "application/json", - dataType: "json", + dataType: "json" }) .done((response) => { var count = @@ -95,14 +95,14 @@ $(() => { new PNotify({ title: "Log Monitor", text: "Wrote " + count + " debug test entries to OctoPrint log.", - type: "success", + type: "success" }); }) .fail(() => { new PNotify({ title: "Log Monitor", text: "Failed to write debug test entries.", - type: "error", + type: "error" }); }); }; @@ -164,7 +164,7 @@ $(() => { WARNING: 0, ERROR: 0, CRITICAL: 0, - UNKNOWN: 0, + UNKNOWN: 0 }); function totalAlerts() { @@ -211,7 +211,7 @@ $(() => { if (count > 0) { parts.push(level + ": " + count); } - }, + } ); return parts.join(" | "); }); @@ -229,7 +229,7 @@ $(() => { if (count > 0) { lines.push(level + ": " + count); } - }, + } ); return "Alerts\n" + lines.join("\n"); @@ -273,7 +273,7 @@ $(() => { return ngettext( "%(count)s history entry", "%(count)s history entries", - count, + count ).replace("%(count)s", count); }); @@ -335,7 +335,7 @@ $(() => { var count = self.alertCount(); return ngettext("%(count)s alert", "%(count)s alerts", count).replace( "%(count)s", - count, + count ); } return gettext("No alerts"); @@ -379,7 +379,7 @@ $(() => { select.empty(); select.append( - $('"), + $('") ); fileNames.forEach((name) => { @@ -474,7 +474,7 @@ $(() => { "):" + renderLogList(activeLogs) + "" + - "", + "" ); }; @@ -494,7 +494,7 @@ $(() => { pluginAjax({ url: pluginBaseUrl + "/alerts/monitor/status", method: "GET", - dataType: "json", + dataType: "json" }) .done((response) => { self.renderAlertMonitorStatus(response); @@ -502,7 +502,7 @@ $(() => { .fail((xhr) => { self.renderAlertMonitorStatus( null, - (xhr && xhr.statusText) || "request failed", + (xhr && xhr.statusText) || "request failed" ); }); }; @@ -540,7 +540,7 @@ $(() => { pluginAjax({ url: pluginBaseUrl + "/files", method: "GET", - dataType: "json", + dataType: "json" }) .done((response) => { var rawFiles = Array.isArray(response && response.files) @@ -564,12 +564,12 @@ $(() => { self.debugLog("Failed to load log file list", { status: xhr && xhr.status, responseText: xhr && xhr.responseText, - url: pluginBaseUrl + "/files", + url: pluginBaseUrl + "/files" }); new PNotify({ title: "Log Monitor", text: "Could not load available log files.", - type: "error", + type: "error" }); }); }; @@ -621,7 +621,7 @@ $(() => { new PNotify({ title: "Log Monitor", text: "Please select a log file first", - type: "error", + type: "error" }); return; } @@ -632,9 +632,9 @@ $(() => { pluginAjax({ url: pluginBaseUrl + "/stream/start", method: "POST", - data: JSON.stringify({ file: streamFile }), + data: JSON.stringify({file: streamFile}), contentType: "application/json", - dataType: "json", + dataType: "json" }) .done((response) => { if (opts.isAutoSwitch) { @@ -663,7 +663,7 @@ $(() => { new PNotify({ title: "Stream Error", text: "Failed to start streaming", - type: "error", + type: "error" }); }) .always(() => { @@ -676,7 +676,7 @@ $(() => { url: pluginBaseUrl + "/stream/stop", method: "POST", contentType: "application/json", - dataType: "json", + dataType: "json" }) .done(() => { clearInterval(flushIntervalId); @@ -689,7 +689,7 @@ $(() => { new PNotify({ title: "Stream Error", text: "Failed to stop streaming", - type: "error", + type: "error" }); }) .always(() => { @@ -749,7 +749,7 @@ $(() => { pieces.push( '' + escapeHtml(matchedText) + - "", + "" ); lastIndex = match.index + matchedText.length; } @@ -806,8 +806,8 @@ $(() => { offset: offset, limit: pageSize, case_sensitive: self.caseSensitive(), - use_regex: self.useRegex(), - }, + use_regex: self.useRegex() + } }) .done((response) => { self.searchResults(response.results); @@ -826,12 +826,12 @@ $(() => { self.debugLog("Search failed", { status: error && error.status, - responseText: error && error.responseText, + responseText: error && error.responseText }); new PNotify({ title: "Search Failed", text: message, - type: "error", + type: "error" }); }) .always(() => { @@ -843,14 +843,14 @@ $(() => { self.previousPage = function () { if (self.canGoPrevious()) { self.currentPage(self.currentPage() - 1); - self.performSearch({ keepPage: true }); + self.performSearch({keepPage: true}); } }; self.nextPage = function () { if (self.canGoNext()) { self.currentPage(self.currentPage() + 1); - self.performSearch({ keepPage: true }); + self.performSearch({keepPage: true}); } }; @@ -860,7 +860,7 @@ $(() => { url: pluginBaseUrl + "/alerts/reset", method: "POST", contentType: "application/json", - dataType: "json", + dataType: "json" }).done(() => { self.alertCounts({ DEBUG: 0, @@ -868,7 +868,7 @@ $(() => { WARNING: 0, ERROR: 0, CRITICAL: 0, - UNKNOWN: 0, + UNKNOWN: 0 }); }); }; @@ -887,12 +887,12 @@ $(() => { method: "POST", data: JSON.stringify({ results: self.searchResults(), - format: safeFormat, + format: safeFormat }), contentType: "application/json", dataType: "text", success: (data) => { - var blob = new Blob([data], { type: "text/plain" }); + var blob = new Blob([data], {type: "text/plain"}); var url = window.URL.createObjectURL(blob); var link = document.createElement("a"); link.href = url; @@ -903,7 +903,7 @@ $(() => { }, error: () => { alert("Failed to export results"); - }, + } }); }; @@ -926,7 +926,7 @@ $(() => { pluginAjax({ url: url, method: "GET", - xhrFields: { responseType: "blob" }, + xhrFields: {responseType: "blob"} }) .done((blob) => { var objectUrl = window.URL.createObjectURL(blob); @@ -948,7 +948,7 @@ $(() => { title: "Log Monitor", text: detail ? base + ": " + detail : base, type: "error", - hide: false, + hide: false }); }; @@ -979,7 +979,7 @@ $(() => { pluginAjax({ url: pluginBaseUrl + "/alert-history", method: "GET", - dataType: "json", + dataType: "json" }).done((response) => { var history = Array.isArray(response && response.history) ? response.history.slice().reverse() @@ -996,7 +996,7 @@ $(() => { url: pluginBaseUrl + "/alert-history/clear", method: "POST", contentType: "application/json", - dataType: "json", + dataType: "json" }).done(() => { self.alertHistory([]); }); @@ -1033,7 +1033,7 @@ $(() => { if (typeof newValue !== "string" || newValue.length === 0) return; if (newValue === self.activeStreamFile()) return; - self.startStream(newValue, { isAutoSwitch: true }); + self.startStream(newValue, {isAutoSwitch: true}); }); if (self.settings.settings.plugins.logmonitor.auto_start_streaming()) { @@ -1110,7 +1110,7 @@ $(() => { new PNotify({ title: "Log Monitor - " + alert.level, text: notificationMessage, - type: pnotifyType, + type: pnotifyType }); } }; @@ -1130,7 +1130,7 @@ $(() => { elements: [ "#tab_plugin_logmonitor", "#navbar_plugin_logmonitor", - "#sidebar_plugin_logmonitor_wrapper", - ], + "#sidebar_plugin_logmonitor_wrapper" + ] }); }); diff --git a/octoprint_logmonitor/templates/logmonitor_settings.jinja2 b/octoprint_logmonitor/templates/logmonitor_settings.jinja2 index 46f6ab5..4d17535 100644 --- a/octoprint_logmonitor/templates/logmonitor_settings.jinja2 +++ b/octoprint_logmonitor/templates/logmonitor_settings.jinja2 @@ -178,7 +178,8 @@ class="input-large" multiple="multiple" size="6" - data-bind="selectedOptions: settings.plugins.logmonitor.alerts_monitored_logs"> + data-bind="selectedOptions: settings.plugins.logmonitor.alerts_monitored_logs"> + {{ _("These logs are monitored for severity triggers even when no live stream is open.") }} @@ -188,7 +189,8 @@
{{ _("Unknown") }} -
{{ _("Status not loaded yet.") }}
+
{{ _("Status not loaded yet.") }}
- +
@@ -191,7 +196,8 @@
- +