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:
+41
-12
@@ -29,6 +29,7 @@ Usage:
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
@@ -36,6 +37,8 @@ from datetime import datetime, time, timedelta
|
||||
|
||||
import glutz_api as g
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# wyby user label: "<last name> <first name> <6-digit transaction>"
|
||||
LABEL_RE = re.compile(r"^.+\s\d{6}$")
|
||||
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:
|
||||
setup_logging()
|
||||
g.load_env()
|
||||
ap = argparse.ArgumentParser(
|
||||
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
|
||||
@@ -102,7 +126,7 @@ def main() -> None:
|
||||
if not isinstance(users, list):
|
||||
sys.exit(f"Unexpected response for UsersGroups: {users!r}")
|
||||
targets = wyby_users(users)
|
||||
print(f"wyby users detected: {len(targets)}")
|
||||
logger.info("wyby users detected: %d", len(targets))
|
||||
|
||||
codes = g.rpc(
|
||||
"eAccess.getModel",
|
||||
@@ -146,23 +170,28 @@ def main() -> None:
|
||||
continue
|
||||
|
||||
planned.append((c, new_vf, new_vt))
|
||||
print(
|
||||
f"PLAN {ctx}: {fmt_ts(vf)} -> {fmt_ts(vt)}"
|
||||
f" => {fmt_ts(new_vf)} -> {fmt_ts(new_vt)}"
|
||||
logger.info(
|
||||
"PLAN %s: %s -> %s => %s -> %s",
|
||||
ctx,
|
||||
fmt_ts(vf),
|
||||
fmt_ts(vt),
|
||||
fmt_ts(new_vf),
|
||||
fmt_ts(new_vt),
|
||||
)
|
||||
|
||||
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:
|
||||
print(f"No changes needed ({len(skipped)} codes checked/skipped).")
|
||||
logger.info("No changes needed (%d codes checked/skipped).", len(skipped))
|
||||
return
|
||||
|
||||
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
|
||||
|
||||
print()
|
||||
for c, new_vf, new_vt in planned:
|
||||
# Preserve existing fields, only change validity.
|
||||
data = {
|
||||
@@ -182,15 +211,15 @@ def main() -> None:
|
||||
res = g.rpc("eAccess.setModel", ["Codes", data])
|
||||
except SystemExit as err: # rpc() reports errors via sys.exit
|
||||
failed.append(ctx)
|
||||
print(f"ERROR {ctx}: {err}")
|
||||
logger.error("ERROR %s: %s", ctx, err)
|
||||
continue
|
||||
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:
|
||||
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:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user