# -*- coding: utf-8 -*-
# @Author: wangkun
# @Time: 2023/7/17
import glob
import datetime
import os.path
import re
import time


class MonitorLogs:

    @classmethod
    def monitor_logs(cls, log_type, crawler):
        # 获取日志文件的路径
        log_files = glob.glob(f"./{crawler}/logs/*-{datetime.datetime.now().date().strftime('%Y-%m-%d')}.log")
        if len(log_files) == 0:
            print("未发现最新日志")
            return
        for log_file in log_files:
            # 检查文件名是否包含"author"且后面带有数字
            if re.search(r"author\d", log_file):
                continue
            # 读取最新日志文件的内容
            with open(log_file, "r") as file:
                logs = file.readlines()
            # 过滤空行日志
            logs = [log.strip() for log in logs if log.strip()]
            # 获取最新一条日志的时间和内容
            latest_log = logs[-1]
            log_time_str = datetime.datetime.strptime(latest_log[:19], "%Y-%m-%d %H:%M:%S")
            log_time_stamp = int(log_time_str.timestamp())
            print("日志文件：", log_file)
            print("最新日志时间：", log_time_str)
            print("最新日志时间戳：", log_time_stamp)
            print("最新日志内容：\n", latest_log[24:])

            if int(time.time()) - log_time_stamp > 60*5:
                print(f"{int(time.time())} - {log_time_stamp} = {int(time.time())-log_time_stamp} > {60 * 5}")


if __name__ == "__main__":
    MonitorLogs.monitor_logs("author", "gongzhonghao")

    pass