35 lines
1.2 KiB
Python
35 lines
1.2 KiB
Python
|
import os
|
|||
|
import datetime
|
|||
|
|
|||
|
class LogHandler:
|
|||
|
""" 日誌處理類別,負責寫入 log 檔案 """
|
|||
|
|
|||
|
def __init__(self, log_dir="logging"):
|
|||
|
""" 初始化 log 系統 """
|
|||
|
self.log_dir = log_dir
|
|||
|
self.ensure_log_directory_exists()
|
|||
|
self.log_file = self.get_log_filename()
|
|||
|
|
|||
|
def ensure_log_directory_exists(self):
|
|||
|
""" 確保 logging 資料夾存在,如果不存在則建立 """
|
|||
|
if not os.path.exists(self.log_dir):
|
|||
|
os.makedirs(self.log_dir)
|
|||
|
|
|||
|
def get_log_filename(self):
|
|||
|
""" 取得今日的 log 檔案名稱(YYYY-MM-DD.txt) """
|
|||
|
today = datetime.datetime.now().strftime("%Y-%m-%d")
|
|||
|
return os.path.join(self.log_dir, f"{today}.txt")
|
|||
|
|
|||
|
def write_log(self, event):
|
|||
|
""" 寫入 log 訊息 """
|
|||
|
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|||
|
log_message = f"[{timestamp}] {event}\n"
|
|||
|
|
|||
|
# 確保 log 檔案是最新的(每天更新)
|
|||
|
self.log_file = self.get_log_filename()
|
|||
|
|
|||
|
with open(self.log_file, "a", encoding="utf-8") as file:
|
|||
|
file.write(log_message)
|
|||
|
|
|||
|
print(f"📄 [LOG] {log_message.strip()}") # 也在 console 顯示 log
|