File size: 740 Bytes
d5f14ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from logging.handlers import RotatingFileHandler

import logging

log_file = '/.cache/app.log'

# 配置 RotatingFileHandler
handler = RotatingFileHandler(log_file, maxBytes=100 * 1024 * 1024, backupCount=3)  # 100MG
handler.setLevel(logging.INFO)
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))

logger = logging.getLogger()
logger.addHandler(handler)


def read_last_n_logs(n, level='ERROR'):
    error_logs = []
    with open(log_file, 'r') as file:
        lines = file.readlines()[-n:]

        # 检查每行日志的级别,只保留 ERROR 级别的日志
        for line in lines:
            if level in line:
                error_logs.append(line.strip())

    return error_logs