44 lines
1.4 KiB
Python
44 lines
1.4 KiB
Python
import csv
|
|
import json
|
|
import os
|
|
from datetime import datetime
|
|
from zoneinfo import ZoneInfo
|
|
|
|
|
|
LOG_DIR = "logs"
|
|
EVENT_LOG_PATH = os.path.join(LOG_DIR, "event_log.csv")
|
|
LOG_COLUMNS = ["date", "time", "user", "action", "status", "details"]
|
|
KST = ZoneInfo("Asia/Seoul")
|
|
|
|
|
|
def user_label(user) -> str:
|
|
if not user:
|
|
return ""
|
|
return getattr(user, "email", None) or getattr(user, "name", None) or str(getattr(user, "id", ""))
|
|
|
|
|
|
def log_event(user, action: str, status: str = "success", details: dict | str | None = None):
|
|
os.makedirs(LOG_DIR, exist_ok=True)
|
|
now = datetime.now(KST)
|
|
file_exists = os.path.exists(EVENT_LOG_PATH)
|
|
details_text = ""
|
|
if isinstance(details, dict):
|
|
details_text = json.dumps(details, ensure_ascii=False)
|
|
elif details is not None:
|
|
details_text = str(details)
|
|
|
|
with open(EVENT_LOG_PATH, "a", encoding="utf-8-sig", newline="") as f:
|
|
writer = csv.DictWriter(f, fieldnames=LOG_COLUMNS)
|
|
if not file_exists or os.path.getsize(EVENT_LOG_PATH) == 0:
|
|
writer.writeheader()
|
|
writer.writerow(
|
|
{
|
|
"date": now.strftime("%Y-%m-%d"),
|
|
"time": now.strftime("%H:%M:%S"),
|
|
"user": user_label(user),
|
|
"action": action,
|
|
"status": status,
|
|
"details": details_text,
|
|
}
|
|
)
|