From ad383b602eac9e64aa1c9e0f2421b8f110b33e4c Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Tue, 6 Oct 2026 23:30:54 +0100 Subject: [PATCH] Configurable logging for the API and worker (SCR-5) Shared LOG_LEVEL/LOG_FORMAT (text or json) set up in create_app, per-task activity and duration logs in the worker, and more context on delivery, inbox and import failures. Alembic's fileConfig no longer disables loggers. Co-Authored-By: Claude Sonnet 5.5 --- .env.example | 4 ++ docker-compose.yml | 4 ++ docs/admin-guide.md | 2 + gunicorn.conf.py | 10 +++++ src/scrobbler/__init__.py | 4 ++ src/scrobbler/cli.py | 1 - src/scrobbler/config.py | 5 +++ src/scrobbler/federation/delivery.py | 17 ++++++++- src/scrobbler/federation/inbox.py | 8 +++- src/scrobbler/logsetup.py | 44 ++++++++++++++++++++++ src/scrobbler/migrations/env.py | 2 +- src/scrobbler/services/art.py | 1 + src/scrobbler/services/imports.py | 2 +- src/scrobbler/worker.py | 30 ++++++++++++++- tests/test_logsetup.py | 56 ++++++++++++++++++++++++++++ tests/test_worker.py | 29 ++++++++++++++ 16 files changed, 212 insertions(+), 7 deletions(-) create mode 100644 src/scrobbler/logsetup.py create mode 100644 tests/test_logsetup.py diff --git a/.env.example b/.env.example index 47558dd..2e4e751 100644 --- a/.env.example +++ b/.env.example @@ -10,6 +10,10 @@ CORS_ORIGINS=http://localhost:8080 # Where Last.fm clients are redirected to approve desktop auth tokens. UI_BASE_URL=http://localhost:8080 +# Logging: level (DEBUG, INFO, WARNING, ERROR) and format ("text", or "json" for log aggregators). +LOG_LEVEL=INFO +LOG_FORMAT=text + # Prometheus metrics are served on a separate port. METRICS_PORT=9100 diff --git a/docker-compose.yml b/docker-compose.yml index ecbfee4..f767e7a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -33,6 +33,8 @@ services: UI_BASE_URL: ${UI_BASE_URL:-http://localhost:8080} WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2} FORWARDED_ALLOW_IPS: "*" + LOG_LEVEL: ${LOG_LEVEL:-INFO} + LOG_FORMAT: ${LOG_FORMAT:-text} LASTFM_API_KEY: ${LASTFM_API_KEY:-} MUSICBRAINZ_CONTACT: ${MUSICBRAINZ_CONTACT:-} ART_STORAGE_DIR: ${ART_STORAGE_DIR:-/data/album-art} @@ -68,6 +70,8 @@ services: FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-} FEDERATION_KEY_SECRET: ${FEDERATION_KEY_SECRET:-} RUN_MIGRATIONS: "0" # the api service applies them + LOG_LEVEL: ${LOG_LEVEL:-INFO} + LOG_FORMAT: ${LOG_FORMAT:-text} expose: - "9101" # metrics: internal network only volumes: diff --git a/docs/admin-guide.md b/docs/admin-guide.md index e521443..9f44958 100644 --- a/docs/admin-guide.md +++ b/docs/admin-guide.md @@ -54,6 +54,8 @@ read **Putting it behind TLS** below — the quick start above serves plain HTTP | `CORS_ORIGINS` | api | `http://localhost:8080` | Comma-separated origins allowed to call `/api/v1`: wherever browsers actually load the UI from | | `UI_BASE_URL` | api | `http://localhost:8080` | Where `/api/auth/` sends users to approve desktop sign-ins, and (with federation on) the public identity users are found under | | `OPENAPI_DOCS_ENABLED` | api | `1` | Set to `0` to hide `/api/docs` and `/api/redoc` | +| `LOG_LEVEL` | api, worker | `INFO` | `DEBUG`, `INFO`, `WARNING` or `ERROR`. The worker logs each task pass that did work at `INFO` (with its duration); idle polls show at `DEBUG` | +| `LOG_FORMAT` | api, worker | `text` | `json` writes one JSON object per line (with `task` and `duration_ms` fields for worker tasks), for log aggregators | | `METRICS_PORT` | api | `9100` | Prometheus metrics port — keep it off the public network | | `WEB_CONCURRENCY` | api | `2` | gunicorn workers | | `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start | diff --git a/gunicorn.conf.py b/gunicorn.conf.py index 31378e8..ad4473b 100644 --- a/gunicorn.conf.py +++ b/gunicorn.conf.py @@ -11,11 +11,21 @@ wsgi_app = "scrobbler:create_app()" bind = os.environ.get("BIND", "0.0.0.0:8000") workers = int(os.environ.get("WEB_CONCURRENCY", "2")) accesslog = "-" +loglevel = os.environ.get("LOG_LEVEL", "INFO").lower() forwarded_allow_ips = os.environ.get("FORWARDED_ALLOW_IPS", "127.0.0.1") # gunicorn 26's control socket lives in $HOME, which the container user doesn't have. control_socket_disable = True +def post_fork(server, worker): + # Gunicorn's own messages go through the app's handler too, so the format is uniform. + import logging + + gunicorn_error = logging.getLogger("gunicorn.error") + gunicorn_error.handlers.clear() + gunicorn_error.propagate = True + + def on_starting(server): # Stale files from a previous run would double-count. shutil.rmtree(MULTIPROC_DIR, ignore_errors=True) diff --git a/src/scrobbler/__init__.py b/src/scrobbler/__init__.py index 59fd4e1..d7a076f 100644 --- a/src/scrobbler/__init__.py +++ b/src/scrobbler/__init__.py @@ -19,6 +19,10 @@ def create_app(config_object=None): app = Flask(__name__, static_folder=None) # API only: the UI is hosted separately app.config.from_object(config_object or Config) + from scrobbler.logsetup import configure_logging + + configure_logging(app.config["LOG_LEVEL"], app.config["LOG_FORMAT"]) + db.init_app(app) migrate.init_app(app, db, directory=_migrations_dir()) http_metrics.init_app(app) diff --git a/src/scrobbler/cli.py b/src/scrobbler/cli.py index 104e021..8e0138e 100644 --- a/src/scrobbler/cli.py +++ b/src/scrobbler/cli.py @@ -8,7 +8,6 @@ from flask.cli import AppGroup, with_appcontext def _run_worker(once: bool, poll: float, serve_metrics: bool) -> None: from scrobbler import worker - logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") if serve_metrics: from scrobbler.metrics.server import start_metrics_server diff --git a/src/scrobbler/config.py b/src/scrobbler/config.py index e86ae1b..1f3f2f5 100644 --- a/src/scrobbler/config.py +++ b/src/scrobbler/config.py @@ -20,6 +20,9 @@ class Config: CORS_ORIGINS = _csv(os.environ.get("CORS_ORIGINS", "http://localhost:8080")) UI_BASE_URL = os.environ.get("UI_BASE_URL", "http://localhost:8080").rstrip("/") + LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper() + LOG_FORMAT = os.environ.get("LOG_FORMAT", "text").lower() # "text" or "json" + METRICS_PORT = int(os.environ.get("METRICS_PORT", "9100")) # Start the metrics HTTP server from create_app (dev server). Under gunicorn the # server is started by gunicorn.conf.py instead, so this stays off there. @@ -92,6 +95,8 @@ class TestConfig(Config): "postgresql+psycopg://scrobbler:scrobbler@localhost:5432/scrobbler_test", ) START_METRICS_SERVER = False + LOG_LEVEL = "INFO" + LOG_FORMAT = "text" # Tests never inherit optional features or URLs from a developer's .env or # environment; tests that need them turn them on, or override them, explicitly. LASTFM_API_KEY = "" diff --git a/src/scrobbler/federation/delivery.py b/src/scrobbler/federation/delivery.py index 07f9da9..7382287 100644 --- a/src/scrobbler/federation/delivery.py +++ b/src/scrobbler/federation/delivery.py @@ -68,6 +68,13 @@ def _retry_or_abandon(delivery: FederationDelivery, error: str, status: int | No delivery.last_status, delivery.last_error = status, error[:1000] if _now() - delivery.created_at >= GIVE_UP_AFTER: delivery.status = "abandoned" + log.warning( + "delivery %s to %s abandoned after %s attempts: %s", + delivery.id, + delivery.inbox, + delivery.attempts, + error[:200], + ) return "abandoned" delay = ( RETRY_DELAYS[delivery.attempts - 1] @@ -75,6 +82,14 @@ def _retry_or_abandon(delivery: FederationDelivery, error: str, status: int | No else LATER_DELAY ) delivery.next_attempt_at = _now() + delay + log.warning( + "delivery %s to %s failed (attempt %s), retrying in %s: %s", + delivery.id, + delivery.inbox, + delivery.attempts, + delay, + error[:200], + ) return "retry" @@ -135,7 +150,7 @@ def _deliver_in_context(app, delivery_id: int) -> str: try: return deliver(delivery_id) except Exception: - log.exception("delivery %s failed unexpectedly", delivery_id) + log.exception("delivery %s failed unexpectedly (will be retried)", delivery_id) db.session.rollback() return "retry" # the lease expires and it becomes due again finally: diff --git a/src/scrobbler/federation/inbox.py b/src/scrobbler/federation/inbox.py index e2f89bd..8f9d8df 100644 --- a/src/scrobbler/federation/inbox.py +++ b/src/scrobbler/federation/inbox.py @@ -224,7 +224,13 @@ def process(item: FederationInboxItem) -> None: db.session.rollback() transient = isinstance(err, FetchError) and err.reason == "network" if not transient: - log.exception("inbox item %s failed", item.id) + log.exception( + "inbox item %s (%s) failed on attempt %s of %s", + item.id, + item.activity_type, + item.attempts, + MAX_ATTEMPTS, + ) if item.attempts < MAX_ATTEMPTS: _finish(item, "queued", f"retrying: {err}"[:255], done=False) return diff --git a/src/scrobbler/logsetup.py b/src/scrobbler/logsetup.py new file mode 100644 index 0000000..8977b52 --- /dev/null +++ b/src/scrobbler/logsetup.py @@ -0,0 +1,44 @@ +"""Logging set-up shared by the API and the worker (`LOG_LEVEL`, `LOG_FORMAT`). + +`text` is human-readable; `json` is one object per line for log aggregators. Fields passed +as `extra=` to a log call (e.g. `task`, `duration_ms`) appear as keys in the JSON output. +""" + +import json +import logging +import sys +from datetime import UTC, datetime + +TEXT_FORMAT = "%(asctime)s %(levelname)s %(name)s %(message)s" + +# Attributes every LogRecord has; anything else on a record came from `extra=`. +_STANDARD = set(logging.makeLogRecord({}).__dict__) | {"message", "asctime", "taskName"} +_HANDLER_FLAG = "_scrobbler_handler" + + +class JsonFormatter(logging.Formatter): + def format(self, record: logging.LogRecord) -> str: + entry = { + "time": datetime.fromtimestamp(record.created, UTC).isoformat(timespec="milliseconds"), + "level": record.levelname, + "logger": record.name, + "message": record.getMessage(), + } + entry.update((k, v) for k, v in record.__dict__.items() if k not in _STANDARD) + if record.exc_info: + entry["exception"] = self.formatException(record.exc_info) + return json.dumps(entry, default=str) + + +def configure_logging(level: str = "INFO", fmt: str = "text") -> None: + """Point the root logger at stderr. Safe to call repeatedly (it replaces its own + handler); an unknown level falls back to INFO.""" + root = logging.getLogger() + for handler in [h for h in root.handlers if getattr(h, _HANDLER_FLAG, False)]: + root.removeHandler(handler) + handler = logging.StreamHandler(sys.stderr) + setattr(handler, _HANDLER_FLAG, True) + handler.setFormatter(JsonFormatter() if fmt == "json" else logging.Formatter(TEXT_FORMAT)) + root.addHandler(handler) + resolved = logging.getLevelName(str(level).upper()) + root.setLevel(resolved if isinstance(resolved, int) else logging.INFO) diff --git a/src/scrobbler/migrations/env.py b/src/scrobbler/migrations/env.py index fc132b9..eb16b68 100644 --- a/src/scrobbler/migrations/env.py +++ b/src/scrobbler/migrations/env.py @@ -11,7 +11,7 @@ config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. -fileConfig(config.config_file_name) +fileConfig(config.config_file_name, disable_existing_loggers=False) logger = logging.getLogger('alembic.env') diff --git a/src/scrobbler/services/art.py b/src/scrobbler/services/art.py index b31077d..2ba9621 100644 --- a/src/scrobbler/services/art.py +++ b/src/scrobbler/services/art.py @@ -602,6 +602,7 @@ def resolve_one_pending() -> bool: row.checked_at = datetime.now(UTC) db.session.commit() metrics.art_worker_resolve_seconds.observe(time.perf_counter() - start) + log.info("album art for %r/%r: %s", row.artist, row.album, result.status) return True diff --git a/src/scrobbler/services/imports.py b/src/scrobbler/services/imports.py index decfba1..d90a50d 100644 --- a/src/scrobbler/services/imports.py +++ b/src/scrobbler/services/imports.py @@ -549,7 +549,7 @@ def process_job(job: ImportJob) -> None: db.session.rollback() _finish(job, "failed", err.message) except Exception: - log.exception("import job %s failed", job.id) + log.exception("import job %s (%s) for user %s failed", job.id, job.source, job.user_id) db.session.rollback() _finish( job, "failed", "The import failed unexpectedly. Try again, or check the server logs." diff --git a/src/scrobbler/worker.py b/src/scrobbler/worker.py index 4ff53b1..6f0cb33 100644 --- a/src/scrobbler/worker.py +++ b/src/scrobbler/worker.py @@ -50,18 +50,44 @@ def registered(app: Flask | None = None) -> list[str]: def _call(task: _Task) -> bool: + started = time.monotonic() try: - worked = bool(task.fn()) + result = task.fn() except Exception: - log.exception("worker task %s failed", task.name) + log.exception( + "worker task %s failed after %.0f ms", + task.name, + _elapsed_ms(started), + extra={"task": task.name, "outcome": "error", "duration_ms": _elapsed_ms(started)}, + ) db.session.rollback() metrics.worker_tasks_total.labels(task=task.name, outcome="error").inc() return False + worked = bool(result) if worked or task.every is not None: metrics.worker_tasks_total.labels(task=task.name, outcome="worked").inc() + duration = _elapsed_ms(started) + # Queue tasks are polled every couple of seconds, so only passes that did work are + # worth an INFO line; periodic tasks say so only when they report work (a truthy result). + log.log( + logging.INFO if worked else logging.DEBUG, + "worker task %s %s in %.0f ms", + task.name, + "worked" if worked else "ran (nothing to do)", + duration, + extra={ + "task": task.name, + "outcome": "worked" if worked else "idle", + "duration_ms": duration, + }, + ) return worked +def _elapsed_ms(started: float) -> float: + return round((time.monotonic() - started) * 1000, 1) + + def run_once() -> bool: """One pass: due periodic tasks, then each queue task once. True if any queue task did work (so there may be more waiting).""" diff --git a/tests/test_logsetup.py b/tests/test_logsetup.py new file mode 100644 index 0000000..f927a03 --- /dev/null +++ b/tests/test_logsetup.py @@ -0,0 +1,56 @@ +import json +import logging + +import pytest + +from scrobbler.logsetup import JsonFormatter, configure_logging + + +@pytest.fixture(autouse=True) +def restore_root_logger(): + root = logging.getLogger() + handlers, level = list(root.handlers), root.level + yield + root.handlers[:] = handlers + root.setLevel(level) + + +def _record(msg="hello %s", args=("world",), **extra): + record = logging.LogRecord("test.logger", logging.INFO, __file__, 1, msg, args, None) + record.__dict__.update(extra) + return record + + +def test_json_formatter_emits_fields_and_extras(): + entry = json.loads(JsonFormatter().format(_record(task="art", duration_ms=12.5))) + assert entry["message"] == "hello world" + assert entry["level"] == "INFO" + assert entry["logger"] == "test.logger" + assert entry["task"] == "art" + assert entry["duration_ms"] == 12.5 + assert "time" in entry + + +def test_json_formatter_includes_exceptions(): + try: + raise ValueError("boom") + except ValueError: + record = _record() + import sys + + record.exc_info = sys.exc_info() + assert "ValueError: boom" in json.loads(JsonFormatter().format(record))["exception"] + + +def test_configure_logging_is_idempotent_and_sets_level(): + root = logging.getLogger() + configure_logging("DEBUG", "json") + configure_logging("warning", "text") + ours = [h for h in root.handlers if getattr(h, "_scrobbler_handler", False)] + assert len(ours) == 1 + assert root.level == logging.WARNING + + +def test_unknown_level_falls_back_to_info(): + configure_logging("LOUD", "text") + assert logging.getLogger().level == logging.INFO diff --git a/tests/test_worker.py b/tests/test_worker.py index fb3ab0d..b0b8558 100644 --- a/tests/test_worker.py +++ b/tests/test_worker.py @@ -89,3 +89,32 @@ def test_worker_cli_lists_and_runs_tasks(app, tasks): assert ran == [1] alias = app.test_cli_runner().invoke(args=["imports", "worker", "--once", "--no-metrics"]) assert alias.exit_code == 0, alias.output + + +def test_a_pass_that_did_work_is_logged_with_its_duration(tasks, caplog): + tasks.register_task("busy", lambda: True) + with caplog.at_level("INFO", logger="scrobbler.worker"): + worker.run_once() + record = next(r for r in caplog.records if r.__dict__.get("task") == "busy") + assert record.levelname == "INFO" + assert record.outcome == "worked" + assert record.duration_ms >= 0 + + +def test_idle_passes_are_only_logged_at_debug(tasks, caplog): + tasks.register_task("idle", lambda: False) + with caplog.at_level("INFO", logger="scrobbler.worker"): + worker.run_once() + assert not [r for r in caplog.records if r.__dict__.get("task") == "idle"] + + +def test_failures_log_the_task_name_and_duration(tasks, caplog): + def boom(): + raise RuntimeError("nope") + + tasks.register_task("broken", boom) + with caplog.at_level("ERROR", logger="scrobbler.worker"): + worker.run_once() + record = next(r for r in caplog.records if r.__dict__.get("task") == "broken") + assert record.outcome == "error" + assert "broken" in record.getMessage()