Spaces:
Build error
Build error
import sys | |
import logging | |
from pathlib import Path | |
import sys | |
import logging | |
from pathlib import Path | |
# 日志重定向类 | |
class Logger: | |
def __init__(self, filename="log.out"): | |
self.log_file = filename | |
self.terminal = sys.stdout | |
self.log = open(self.log_file, "w") | |
def write(self, message): | |
self.terminal.write(message) | |
self.log.write(message) | |
def flush(self): | |
self.terminal.flush() | |
self.log.flush() | |
def isatty(self): | |
return False | |
# 设置日志处理器 | |
def setup_logger(log_file_path): | |
# 创建日志文件 | |
log_file = Path(log_file_path) | |
log_file.parent.mkdir(parents=True, exist_ok=True) | |
# 重定向 stdout 和 stderr 到日志文件 | |
sys.stdout = Logger(str(log_file)) | |
sys.stderr = sys.stdout | |
# 配置日志格式 | |
logging.basicConfig( | |
level=logging.INFO, | |
format="%(asctime)s [%(levelname)s] %(message)s", | |
handlers=[ | |
logging.StreamHandler(sys.stdout) | |
] | |
) | |
def read_logs(log_file_path): | |
sys.stdout.flush() | |
with open(log_file_path, "r") as f: | |
return f.read() | |
# Clear logs | |
def remove_log_file(file_path): | |
log_file = Path(file_path) | |
if log_file.exists() and log_file.is_file(): | |
log_file.unlink() |