feat: enhance logging detail across all modules

- email_client: log IMAP connection, login, UNSEEN count, each email
  details (subject/sender/body size), mark-as-seen progress
- ai_client: log AI request params, timing, token usage, response size
- smtp_client: log SMTP connect, login, send details
- tg_bot: log all callback actions with subject context, message states
- main: periodic queue depth report (email_queue/tg_queue/pending_uids)
This commit is contained in:
2026-07-02 21:00:40 +08:00
parent 934d6a7545
commit d334b6f3eb
5 changed files with 65 additions and 3 deletions

View File

@@ -1,11 +1,14 @@
import imaplib
import email
import logging
from email.header import decode_header
from email.utils import parsedate_to_datetime
from typing import Optional
from src.config import EmailAccount
from src.retry import retry
logger = logging.getLogger(__name__)
class Email:
def __init__(self, uid: bytes, subject: str, sender: str, body: str, date: str):
@@ -69,11 +72,15 @@ def _select_mailbox(conn, mailbox: str = "INBOX"):
def _login_and_prepare(account: EmailAccount):
logger.info("连接 %s:%d", account.imap_server, account.imap_port)
conn = imaplib.IMAP4_SSL(account.imap_server, account.imap_port)
conn.login(account.username, account.password)
logger.info("登录成功: %s", account.username)
if _check_provider(account.username, _PROVIDERS_NEED_ID):
logger.info("发送 ID 命令 (126/163 兼容)")
_send_id_command(conn)
_select_mailbox(conn)
logger.info("已选择 INBOX")
return conn
@@ -83,11 +90,13 @@ def fetch_unseen_emails(account: EmailAccount) -> list[Email]:
_, data = conn.uid("SEARCH", None, "UNSEEN")
uids = data[0].split() if data[0] else []
logger.info("UNSEEN 数量: %d", len(uids))
emails = []
for uid in uids:
_, msg_data = conn.uid("FETCH", uid, "RFC822")
if msg_data[0] is None:
logger.warning("UID %s FETCH 返回空,跳过", uid)
continue
raw_email = msg_data[0][1]
msg = email.message_from_bytes(raw_email)
@@ -96,10 +105,13 @@ def fetch_unseen_emails(account: EmailAccount) -> list[Email]:
sender = _decode_str(msg.get("From", ""))
date_str = msg.get("Date", "")
body = _get_text_from_msg(msg)
body_len = len(body)
logger.info(" 邮件: [%s] %s <%s> (%d 字符)", subject, sender, date_str, body_len)
emails.append(Email(uid=uid, subject=subject, sender=sender, body=body, date=date_str))
conn.logout()
logger.info("共获取 %d 封新邮件", len(emails))
return emails
@@ -107,7 +119,9 @@ def fetch_unseen_emails(account: EmailAccount) -> list[Email]:
def mark_as_seen(account: EmailAccount, uids: list[bytes]):
if not uids:
return
logger.info("标记 %d 封邮件为已读", len(uids))
conn = _login_and_prepare(account)
for uid in uids:
conn.uid("STORE", uid, "+FLAGS", "\\Seen")
conn.logout()
logger.info("标记完成")