File size: 1,668 Bytes
f3500d2
af9c5ac
f3500d2
 
af9c5ac
ceeca9e
 
 
 
 
 
af9c5ac
f3500d2
af9c5ac
f3500d2
 
 
 
 
 
 
 
 
 
 
 
 
5e021d4
f3500d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af9c5ac
 
ceeca9e
5e021d4
ceeca9e
f3500d2
ceeca9e
f3500d2
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
57
import io
import json
import logging


def read_all_text(file_path: str) -> str:
    with open(file_path, "r", encoding="utf-8") as file:
        content = file.read()
    return content


def dump_jsonl(path, data):
    with open(path, "w") as f:
        for item in data:
            f.write(
                json.dumps(item, indent=2, ensure_ascii=False) + "\n"
            )


class RealTimeLogCapture:
    """实时日志捕获器,使用StringIO方式"""
    def __init__(self, logger_name=None):
        self.log_stream = io.StringIO()
        self.logger = logging.getLogger(logger_name) if logger_name else logging.getLogger()
        
        # 创建处理器和格式器
        self.handler = logging.StreamHandler(self.log_stream)
        formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(pathname)s:%(lineno)d - %(message)s", 
                                    datefmt='%Y-%m-%d %H:%M:%S')
        self.handler.setFormatter(formatter)
        
        # 添加处理器到logger
        self.logger.addHandler(self.handler)
        self.logger.setLevel(logging.INFO)
        
    def get_logs(self):
        """获取当前所有日志内容"""
        return self.log_stream.getvalue()
    
    def clear_logs(self):
        """清空日志内容"""
        self.log_stream.truncate(0)
        self.log_stream.seek(0)
    
    def cleanup(self):
        """清理资源"""
        self.logger.removeHandler(self.handler)
        self.handler.close()


if __name__ == "__main__":
    file_path = "your_path"  # 请替换为实际的文件路径
    text = read_all_text(file_path)
    print("-" * 20)
    print(text)
    print("-" * 20)