50 lines
1.0 KiB
Python
50 lines
1.0 KiB
Python
from datetime import datetime
|
|
from enum import Enum
|
|
import threading
|
|
|
|
from core.eventbus import EventPrintLog, event_bus
|
|
import config
|
|
|
|
|
|
class LogLevel(Enum):
|
|
DEBUG = 0
|
|
INFO = 1
|
|
WARNING = 2
|
|
ERROR = 3
|
|
CRITICAL = 4
|
|
|
|
def __le__(self, other):
|
|
return self.value <= other.value
|
|
|
|
|
|
class LogData:
|
|
def __init__(self, level: LogLevel, message: str):
|
|
self.level = level
|
|
self.message = message
|
|
|
|
|
|
_log_lock = threading.Lock()
|
|
|
|
|
|
def _log_file_path():
|
|
"""日志文件路径"""
|
|
return str(config.log_file_path())
|
|
|
|
|
|
def PrintLog(level: LogLevel, message: str):
|
|
data = LogData(level, message)
|
|
event_bus.publish(EventPrintLog, data)
|
|
|
|
line = f'{datetime.now().strftime("%Y-%m-%d %H:%M:%S")} [{level.name}] {message}'
|
|
|
|
if config.console_log:
|
|
print(line)
|
|
|
|
# 写入日志文件
|
|
try:
|
|
with _log_lock:
|
|
with open(_log_file_path(), 'a', encoding='utf-8') as f:
|
|
f.write(line + '\n')
|
|
except Exception:
|
|
pass # 写文件失败不阻塞主流程
|