Add structured logging via stdlib logging module
- INFO -> stdout (journal priority info), WARNING/ERROR -> stderr (err) - no-validity-window skip for wyby users is now a WARNING (interface bug hint) - setup_logging(force=True) rebinding handlers, covered by tests - SyslogIdentifier in systemd unit; README logging section (German)
This commit is contained in:
@@ -62,6 +62,31 @@ den Buchungsbeginn ab.
|
|||||||
`glutz-maintenances.timer` (`OnCalendar=*-*-* 05..23:40:00`)
|
`glutz-maintenances.timer` (`OnCalendar=*-*-* 05..23:40:00`)
|
||||||
- Logs: `journalctl -u glutz-maintenances.service`
|
- Logs: `journalctl -u glutz-maintenances.service`
|
||||||
|
|
||||||
|
## Logging
|
||||||
|
|
||||||
|
Das Script loggt über das Python-`logging`-Modul nach stdout/stderr; journald
|
||||||
|
übernimmt Persistenz, Rotation und Abfrage. Kein eigenes Logfile nötig.
|
||||||
|
|
||||||
|
- **INFO → stdout** (Journal-Priority «info»): normaler Ablauf — erkannte
|
||||||
|
Benutzer, PLAN/SKIP je Code, Ergebnis
|
||||||
|
- **WARNING/ERROR → stderr** (Priority «err»): auffällig/fehlerhaft
|
||||||
|
- WARNING «no validity window»: wyby-Benutzer mit Code ohne Fenster —
|
||||||
|
Hinweis auf Schnittstellen-Problem (siehe Doku 3.1 im
|
||||||
|
`../glutz-eaccess-api/wyby-glutz-integration.md`)
|
||||||
|
- ERROR: Schreibfehler → Lauf endet mit Exit-Code 1
|
||||||
|
(`systemctl is-failed glutz-maintenances.service` schlägt an)
|
||||||
|
|
||||||
|
Abfragen:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
journalctl -u glutz-maintenances.service # alle Läufe
|
||||||
|
journalctl -t glutz-maintenances -p err # nur Fehler
|
||||||
|
journalctl -t glutz-maintenances --since today # heutige Läufe
|
||||||
|
sudo journalctl -u glutz-maintenances.service -f # live mitverfolgen
|
||||||
|
```
|
||||||
|
|
||||||
|
Das Journal ist persistent (`/var/log/journal`), überlebt also Reboots.
|
||||||
|
|
||||||
## Verifikation (Testbuchung)
|
## Verifikation (Testbuchung)
|
||||||
|
|
||||||
1. Testbuchung im wyby-Portal erfassen → Schnittstelle legt Benutzer + PIN an.
|
1. Testbuchung im wyby-Portal erfassen → Schnittstelle legt Benutzer + PIN an.
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ User=apps
|
|||||||
Group=users
|
Group=users
|
||||||
WorkingDirectory=/home/apps/glutz-maintenances
|
WorkingDirectory=/home/apps/glutz-maintenances
|
||||||
ExecStart=/usr/bin/python3 /home/apps/glutz-maintenances/extend_pins.py --apply
|
ExecStart=/usr/bin/python3 /home/apps/glutz-maintenances/extend_pins.py --apply
|
||||||
|
SyslogIdentifier=glutz-maintenances
|
||||||
NoNewPrivileges=true
|
NoNewPrivileges=true
|
||||||
ProtectSystem=full
|
ProtectSystem=full
|
||||||
ProtectHome=read-only
|
ProtectHome=read-only
|
||||||
|
|||||||
+41
-12
@@ -29,6 +29,7 @@ Usage:
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
|
import logging
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
@@ -36,6 +37,8 @@ from datetime import datetime, time, timedelta
|
|||||||
|
|
||||||
import glutz_api as g
|
import glutz_api as g
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# wyby user label: "<last name> <first name> <6-digit transaction>"
|
# wyby user label: "<last name> <first name> <6-digit transaction>"
|
||||||
LABEL_RE = re.compile(r"^.+\s\d{6}$")
|
LABEL_RE = re.compile(r"^.+\s\d{6}$")
|
||||||
END_OF_DAY = time(23, 59, 59)
|
END_OF_DAY = time(23, 59, 59)
|
||||||
@@ -77,7 +80,28 @@ def full_day_window(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def setup_logging() -> None:
|
||||||
|
"""Route INFO to stdout, WARNING/ERROR to stderr.
|
||||||
|
|
||||||
|
systemd captures stdout at journal priority "info" and stderr at "err",
|
||||||
|
so `journalctl -p err -u glutz-maintenances` shows real problems only.
|
||||||
|
No timestamps in the format: journald adds them.
|
||||||
|
"""
|
||||||
|
stdout = logging.StreamHandler(sys.stdout)
|
||||||
|
stdout.setLevel(logging.INFO)
|
||||||
|
stdout.addFilter(lambda record: record.levelno < logging.WARNING)
|
||||||
|
stderr = logging.StreamHandler(sys.stderr)
|
||||||
|
stderr.setLevel(logging.WARNING)
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(levelname)s: %(message)s",
|
||||||
|
handlers=[stdout, stderr],
|
||||||
|
force=True, # rebind handlers to the current streams on every call
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
|
setup_logging()
|
||||||
g.load_env()
|
g.load_env()
|
||||||
ap = argparse.ArgumentParser(
|
ap = argparse.ArgumentParser(
|
||||||
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
|
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
|
||||||
@@ -102,7 +126,7 @@ def main() -> None:
|
|||||||
if not isinstance(users, list):
|
if not isinstance(users, list):
|
||||||
sys.exit(f"Unexpected response for UsersGroups: {users!r}")
|
sys.exit(f"Unexpected response for UsersGroups: {users!r}")
|
||||||
targets = wyby_users(users)
|
targets = wyby_users(users)
|
||||||
print(f"wyby users detected: {len(targets)}")
|
logger.info("wyby users detected: %d", len(targets))
|
||||||
|
|
||||||
codes = g.rpc(
|
codes = g.rpc(
|
||||||
"eAccess.getModel",
|
"eAccess.getModel",
|
||||||
@@ -146,23 +170,28 @@ def main() -> None:
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
planned.append((c, new_vf, new_vt))
|
planned.append((c, new_vf, new_vt))
|
||||||
print(
|
logger.info(
|
||||||
f"PLAN {ctx}: {fmt_ts(vf)} -> {fmt_ts(vt)}"
|
"PLAN %s: %s -> %s => %s -> %s",
|
||||||
f" => {fmt_ts(new_vf)} -> {fmt_ts(new_vt)}"
|
ctx,
|
||||||
|
fmt_ts(vf),
|
||||||
|
fmt_ts(vt),
|
||||||
|
fmt_ts(new_vf),
|
||||||
|
fmt_ts(new_vt),
|
||||||
)
|
)
|
||||||
|
|
||||||
for s in skipped:
|
for s in skipped:
|
||||||
print(f"SKIP {s}")
|
# A wyby user without a validity window hints at an interface problem
|
||||||
|
# (see glutz-eaccess-api docs, section 3.1) - surface it as WARNING.
|
||||||
|
(logger.warning if "no validity window" in s else logger.info)("SKIP %s", s)
|
||||||
|
|
||||||
if not planned:
|
if not planned:
|
||||||
print(f"No changes needed ({len(skipped)} codes checked/skipped).")
|
logger.info("No changes needed (%d codes checked/skipped).", len(skipped))
|
||||||
return
|
return
|
||||||
|
|
||||||
if not args.apply:
|
if not args.apply:
|
||||||
print(f"\nDRY-RUN: {len(planned)} change(s) planned, nothing written.")
|
logger.info("DRY-RUN: %d change(s) planned, nothing written.", len(planned))
|
||||||
return
|
return
|
||||||
|
|
||||||
print()
|
|
||||||
for c, new_vf, new_vt in planned:
|
for c, new_vf, new_vt in planned:
|
||||||
# Preserve existing fields, only change validity.
|
# Preserve existing fields, only change validity.
|
||||||
data = {
|
data = {
|
||||||
@@ -182,15 +211,15 @@ def main() -> None:
|
|||||||
res = g.rpc("eAccess.setModel", ["Codes", data])
|
res = g.rpc("eAccess.setModel", ["Codes", data])
|
||||||
except SystemExit as err: # rpc() reports errors via sys.exit
|
except SystemExit as err: # rpc() reports errors via sys.exit
|
||||||
failed.append(ctx)
|
failed.append(ctx)
|
||||||
print(f"ERROR {ctx}: {err}")
|
logger.error("ERROR %s: %s", ctx, err)
|
||||||
continue
|
continue
|
||||||
if res.get("id"):
|
if res.get("id"):
|
||||||
print(f"OK {ctx}: -> {fmt_ts(new_vf)} ... {fmt_ts(new_vt)}")
|
logger.info("OK %s: -> %s ... %s", ctx, fmt_ts(new_vf), fmt_ts(new_vt))
|
||||||
else:
|
else:
|
||||||
failed.append(ctx)
|
failed.append(ctx)
|
||||||
print(f"UNCLEAR {ctx}: response without id: {res!r}")
|
logger.error("UNCLEAR %s: response without id: %r", ctx, res)
|
||||||
|
|
||||||
print(f"\n{len(planned) - len(failed)}/{len(planned)} changed.")
|
logger.info("%d/%d changed.", len(planned) - len(failed), len(planned))
|
||||||
if failed:
|
if failed:
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
|
|||||||
@@ -168,13 +168,29 @@ class TestMainApply:
|
|||||||
calls = install_rpc(codes=codes)
|
calls = install_rpc(codes=codes)
|
||||||
run_main(monkeypatch, "--apply")
|
run_main(monkeypatch, "--apply")
|
||||||
|
|
||||||
out = capsys.readouterr().out
|
captured = capsys.readouterr()
|
||||||
writes = [p for m, p in calls if m == "eAccess.setModel"]
|
writes = [p for m, p in calls if m == "eAccess.setModel"]
|
||||||
assert len(writes) == 1
|
assert len(writes) == 1
|
||||||
assert writes[0][1]["id"] == "1"
|
assert writes[0][1]["id"] == "1"
|
||||||
assert "no validity window" in out
|
assert "no validity window" in captured.err # suspicious -> WARNING
|
||||||
assert "already full-day" in out
|
assert "already full-day" in captured.out
|
||||||
assert "already expired" in out
|
assert "already expired" in captured.out
|
||||||
|
|
||||||
|
def test_log_routing_info_stdout_problems_stderr(
|
||||||
|
self, install_rpc, monkeypatch, capsys
|
||||||
|
):
|
||||||
|
codes = [
|
||||||
|
code_row(id=1),
|
||||||
|
code_row(id=2, code="111111", validFrom=None, validTo=None),
|
||||||
|
]
|
||||||
|
install_rpc(codes=codes)
|
||||||
|
run_main(monkeypatch)
|
||||||
|
|
||||||
|
captured = capsys.readouterr()
|
||||||
|
assert "PLAN" in captured.out
|
||||||
|
assert "PLAN" not in captured.err
|
||||||
|
assert "no validity window" in captured.err
|
||||||
|
assert "no validity window" not in captured.out
|
||||||
|
|
||||||
def test_only_code_filter(self, install_rpc, monkeypatch, capsys):
|
def test_only_code_filter(self, install_rpc, monkeypatch, capsys):
|
||||||
codes = [code_row(id=1, code="225313"), code_row(id=2, code="999999")]
|
codes = [code_row(id=1, code="225313"), code_row(id=2, code="999999")]
|
||||||
@@ -185,14 +201,20 @@ class TestMainApply:
|
|||||||
assert len(writes) == 1
|
assert len(writes) == 1
|
||||||
assert writes[0][1]["code"] == "999999"
|
assert writes[0][1]["code"] == "999999"
|
||||||
|
|
||||||
def test_write_result_without_id_counts_as_failure(self, install_rpc, monkeypatch):
|
def test_write_result_without_id_counts_as_failure(
|
||||||
|
self, install_rpc, monkeypatch, capsys
|
||||||
|
):
|
||||||
install_rpc(codes=[code_row()], write_result={})
|
install_rpc(codes=[code_row()], write_result={})
|
||||||
with pytest.raises(SystemExit) as excinfo:
|
with pytest.raises(SystemExit) as excinfo:
|
||||||
run_main(monkeypatch, "--apply")
|
run_main(monkeypatch, "--apply")
|
||||||
assert excinfo.value.code == 1
|
assert excinfo.value.code == 1
|
||||||
|
assert "UNCLEAR" in capsys.readouterr().err
|
||||||
|
|
||||||
def test_rpc_error_during_write_exits_nonzero(self, install_rpc, monkeypatch):
|
def test_rpc_error_during_write_exits_nonzero(
|
||||||
|
self, install_rpc, monkeypatch, capsys
|
||||||
|
):
|
||||||
install_rpc(codes=[code_row()], write_error="HTTP 500: boom")
|
install_rpc(codes=[code_row()], write_error="HTTP 500: boom")
|
||||||
with pytest.raises(SystemExit) as excinfo:
|
with pytest.raises(SystemExit) as excinfo:
|
||||||
run_main(monkeypatch, "--apply")
|
run_main(monkeypatch, "--apply")
|
||||||
assert excinfo.value.code == 1
|
assert excinfo.value.code == 1
|
||||||
|
assert "ERROR" in capsys.readouterr().err
|
||||||
|
|||||||
Reference in New Issue
Block a user