Python实现 tail -f 功能
笔者工作中需要监控线上机器的日志,然后读取每一行日志进行处理。
在Linux机器上,使用如下的指令可以实时监控日志的产生。
tail -f test.log
使用tail命令的-f选项可以方便地查阅正在改变的日志文件,会把所监控文件最尾部的内容显示在屏幕上,并且不断刷新。
而笔者需要实时得获取新增的日志,并且进行分析处理。
直接上Python代码。
#log的路径 test_log = "/home/work/test/test.log" def main(self): test_log.seek(0,2)#从文件末尾开始读 while True: where = test_log.tell()#获取文件末尾的位置 log_line = test_log.readline().strip()#读取一行 if not log_line: test_log.seek(where) else: print log_line if __name__ == "__main__": main()
但笔者也发现一个问题,由于所监控的文件每秒会新增6K多行的日志,所以有时会出现打印出的日志行不完整的现象。
目前看到,使用如下的方法,可以解决这个问题。
#log的路径 test_log = "/home/work/test/test.log" def main(self): test_log.seek(0,2)#从文件末尾开始读 log_line = test_log.readline() while True: if log_line.endswith("\n"): #可以加上处理逻辑 print log_line log_line = test_log.readline() else: log_line += test_log.readline() if __name__ == "__main__": main()

浙公网安备 33010602011771号