分享一个Python 写的监控日志log txt文档 的代码

监控log文件的需求

某些特殊原因,想一直看到.log 的最后一行打印,所以写了一些代码监控log

(有个奇怪需求,就是log 因为重复启动原因,会一直加,不是同一个log)

监控界面

涉及的Python代码,

有需要的拿去吧

  • 时间戳
  • unicode - 没用上(python 3)
  • 文件夹遍历
  • 读取文件夹
  • enumerate() 方法
  • while 循环 +sleep(1)
python 复制代码
# 相关的Renderdoc 关于glsl shader的逆向代码 ,非Python:https://blog.csdn.net/avi9111/article/details/132798279?spm=1001.2014.3001.5502
# Notices:
# 1. the 3rd parameter of open() is to disable file buffering
#      so file updated by another process could be picked up correctly
#      but since your focus is newly added tail, enable buffering is ok too
# 2. It is not necessary to fh.tell() to save the position, and then seek()
#     to resume, as if readline() failed, the pointer stay still at the EOF

import sys
import time
import os
if sys.version_info[0] >= 3:
    unicode = str
'''获取文件的创建时间'''
#模型奇妙 https://www.cnpython.com/qa/153573
def get_FileCreateTime(filePath):
    #filePath = unicode(filePath,encoding='utf8')#Python 3 renamed the unicode type to str,
    t = os.path.getctime(filePath)
    #return TimeStampToTime(t)
    return t
#获取文件内容(info),参考:https://blog.csdn.net/HeatDeath/article/details/79526037
def checkLatestLog(folder):
    files = os.listdir(folder)
    
    name_latest = ''
    t_latest = -1
    for i,n in enumerate(files):#这个 i 没什么用,就是写着玩
        t = get_FileCreateTime(folder+"\\" + n)#这个拼接代码应该在 win 平台,才能用
        if t>t_latest:
            t_latest = t
            name_latest = n
    return folder +"\\" + name_latest#这个代码应该在 win 平台,才能用
        
filename = sys.argv[1]#全路径吧,(要是相对路径。。。本来可以,现在应该会有问题 ,下面套了逻辑)
print("...open..."+filename)
thisFilePath= filename
#就是一个很普通的update 循环,也可以不用 with open() 套外面,不过之前代码就是这个逻辑
with open(filename) as fh:
#with open(filename, 'r', 0) as fh:
#with os.fdopen(filename,'wb',0) as fh:
    while True: 
        line = fh.readline()
        if not line:
            time.sleep(1)
            # 加了一个逻辑==判断当前文件夹是否有最新日志
            logFilePath = checkLatestLog(os.path.dirname(filename))
            if(logFilePath!=thisFilePath):
                fh = open(logFilePath)
                thisFilePath = logFilePath
                print(".............. 换了一个 log .............." + logFilePath)

        else:
            print(line)
相关推荐
luj_176832 分钟前
变频技术核心原理揭秘
服务器·c语言·开发语言·经验分享·算法
coder_Eight32 分钟前
从 3 天到 8 分钟:我如何把垂直科普内容做成了自动化流水线
python·ai编程
水獭比特32 分钟前
MCP SDK v2 迁移别只改依赖:先把 FastMCP 3/4 拆成两条测试线
人工智能·python
l12586538 分钟前
# RAG多轮对话检索设计:Query重写如何让“那它呢“变成完整问题
前端·数据库·人工智能·python·算法·fastapi·milvus
dorky-org1 小时前
03-Python基础
python·具身智能
如此这般英俊1 小时前
手搓Claude Code-第十三章 background_tasks
前端·人工智能·chrome·python·算法·语言模型·自然语言处理
君顾11 小时前
智慧场馆解决方案小程序系统开发实战指南
java·开发语言·智慧场馆
Είναι η κοπέλα1 小时前
PyTorch 模型导出与部署实战:ONNX + onnxruntime(可直接落地)
人工智能·pytorch·python
NutShell Wang1 小时前
Mojo 1.0 实战:把 Python 热路径原地加速到 C++ 级(四层渐进式迁移)
python·mojo·vibe coding
运维行者_2 小时前
预测性云监控怎么做?AI驱动的7大核心能力与落地路径
服务器·开发语言·网络·数据库·人工智能·python·php