zoukankan      html  css  js  c++  java
  • 实时监控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

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

  • 相关阅读:
    哪怕我变成一个庸俗女子
    硬盘接口的种类
    HTTPS与SHTTP
    Jquery动态加载页面
    iText简介
    TFS offline issue
    VS2008 调试慢的问题
    One error related to msxml4.dll (0x800C0014)
    46 Run Commands for Frequently Used Areas of Your Windows Computer
    快速启动工具入门——以Launchy为例(二)
  • 原文地址:https://www.cnblogs.com/baiyanhuang/p/3832906.html
Copyright © 2011-2022 走看看