实时监控log文件

一个进程在运行,并在不断的写log,你需要实时监控log文件的更新(一般是debug时用),怎么办,不断的打开,关闭文件吗? 不用,至少有两个方法,来自两个很常用的命令:

  1. tail -f log.txt, 另外一个进程在写log,而你用tail,就可以实时的打印出新的内容
  2. less log.txt, 然后如果要监控更新,按F,如果要暂停监控,可以CTRL+C, 这样就可以上下翻页查看,要继续监控了再按F即可。这个功能要比tail更强。

可以很容易的模拟一下:

  1. 在一个shell中持续更新文件:
     $ count=1; while true; do echo hello, world $count >> log.txt; count=$(($count+1)); sleep 1s; done
  2. 在另一个shell中tail -f log.txt or less log.txt

 

写一个类似于tail的程序,其实也蛮简单的:

复制代码
# 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

filename = sys.argv[1]

with open(filename, 'r', 0) as fh:
    while True:
        line = fh.readline()
        if not line:
            time.sleep(1)
        else:
            print line
复制代码

这个可以做为一个不错的面试题。

posted @   lzprgmr  阅读(5385)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?

黄将军

点击右上角即可分享
微信分享提示