File size: 1,295 Bytes
1207342
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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()