# -*- coding: utf-8 -*- """美团酒店采集埋点(只写本地 JSONL,不落库、不建表)。 设计约束(见 dashboard/docs/05_采集端埋点需求.md): 1. 任何异常都被吞掉:写日志失败只表现为“少一条日志”,绝不影响采集主流程; 2. 纯本地文件追加,无网络、无数据库、无重试、不阻塞; 3. 按天分文件:logs/run_YYYYMMDD.jsonl,跨零点自动换文件; 4. 脱敏:dfpid 只写后 8 位;msg 截断 200 字;不写 headers/token/代理密码。 关闭开关:环境变量 HOTEL_INSIGHT_OFF=1 """ import json import os from datetime import datetime LOG_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs") _TAIL = 8 # dfpid 保留位数 _MSG_MAX = 200 _NAME_MAX = 60 def enabled() -> bool: return os.environ.get("HOTEL_INSIGHT_OFF", "") != "1" def log_path(now: datetime = None) -> str: now = now or datetime.now() return os.path.join(LOG_DIR, "run_%s.jsonl" % now.strftime("%Y%m%d")) def _tail(value) -> str: """dfpid → 后 8 位(字符串化后截断,None → 空)。""" if not value: return "" text = str(value) return text[-_TAIL:] if len(text) > _TAIL else text def _cut(value, limit: int) -> str: if value is None: return "" text = str(value) return text[:limit] def _as_dict(value): """把可能为 str 的响应体转成 dict;失败返回空 dict。""" if isinstance(value, dict): return value if isinstance(value, str): try: parsed = json.loads(value) return parsed if isinstance(parsed, dict) else {} except (ValueError, TypeError): return {} return {} def _write(record: dict) -> None: if not enabled(): return try: os.makedirs(LOG_DIR, exist_ok=True) with open(log_path(), "a", encoding="utf-8") as f: f.write(json.dumps(record, ensure_ascii=False) + "\n") except Exception: # 埋点永不抛异常 pass def log_event(event: str, *, hd_id=None, dfpid=None, bind_city=None, target_city=None, city_name=None, hotel_id=None, hotel_name=None, unique_id=None, code=None, ok=None, msg=None) -> None: """写一条事件。字段白名单见 05 文档第 3 节。""" record = { "ts": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"), "event": event, "hd_id": hd_id, "dfpid_tail": _tail(dfpid), "bind_city": bind_city, "target_city": target_city, "city_name": city_name, "hotel_id": None if hotel_id is None else str(hotel_id), "hotel_name": _cut(hotel_name, _NAME_MAX) or None, "unique_id": None if unique_id is None else str(unique_id), "code": code, "ok": ok, "msg": _cut(msg, _MSG_MAX) or None, } _write(record) def log_fetch(hd_id, dfpid, bind_city, target_city, task) -> None: """领到任务:task 为 get_one_task() 的返回体(含 data)。""" data = (_as_dict(task).get("data") or {}) if task else {} if not isinstance(data, dict): data = {} log_event( "fetch_task", hd_id=hd_id, dfpid=dfpid, bind_city=bind_city, target_city=target_city, city_name=data.get("cityName"), hotel_id=data.get("hotelId"), hotel_name=data.get("hotelName"), unique_id=data.get("uniqueId"), ok=1, ) def log_fetch_empty(hd_id, dfpid, bind_city, target_city, resp=None, note: str = "") -> None: """没领到任务:resp 可能是 False / None / dict(含 code、message)。""" if resp is None or resp is False: code, message = None, note or "城市未匹配" else: body = _as_dict(resp) code = body.get("code") message = body.get("message") or body.get("msg") or note or "" log_event( "fetch_empty", hd_id=hd_id, dfpid=dfpid, bind_city=bind_city, target_city=target_city, code=code if isinstance(code, int) else None, ok=0, msg=message, ) def log_upload(hd_id, dfpid, target_city, resp, unique_id=None, city_name=None) -> None: """交任务结果:resp 为 upload_task_datagram() 的返回体。""" body = _as_dict(resp) code = body.get("code") ok = 1 if code == 0 else 0 log_event( "upload", hd_id=hd_id, dfpid=dfpid, target_city=target_city, city_name=city_name, unique_id=unique_id, code=code if isinstance(code, int) else None, ok=ok, msg=body.get("message") or body.get("msg"), ) def log_exception(hd_id, dfpid, target_city, exc, code=None) -> None: """异常:exc 可以是异常对象,也可以是错误文案(如 'Unauthorized(401)')。""" if isinstance(exc, BaseException): text = "%s: %s" % (type(exc).__name__, exc) elif exc is None: text = "" else: text = str(exc) log_event( "exception", hd_id=hd_id, dfpid=dfpid, target_city=target_city, code=code, ok=0, msg=text, )