tail -f命令不能自动切换切片文件,例如日志是每100M生成一个新文件,tail -f不能自动的切换文件,必须关闭然后重新运行tail -f

此篇使用pyinotify,检测文件更新,并实现tail -f以外,还能自动识别切换切片文件。而且针对日志类型的文件做了单独样式优化。

运行 ./tailf.py + 文件路径。

此文件够自动从普通文本中,对日志就行着色处理,如果不是日志类型的文件,将直接输出,不进行着色处理。

tailf.py文件的实现代码如下:

 
import os
import sys
import re
import pyinotify DIRMASK = pyinotify.IN_MODIFY \
| pyinotify.IN_ATTRIB \
| pyinotify.IN_MOVE_SELF \
| pyinotify.IN_CREATE class Handler(pyinotify.ProcessEvent): def __init__(self, filename):
self._fh = None
self._path = filename super(Handler, self).__init__() def my_init(self):
try:
self._fh = open(self._path, 'r')
except IOError as e:
sys.stderr.write('open file failed, %s' % e)
else:
self._fh.seek(0, 2) def process_IN_CREATE(self, event):
path = self._path if path in os.path.join(event.path, event.name):
if hasattr(self, 'fh'):
self._fh.close() try:
self._fh = open(self._path, 'r')
except IOError as e:
sys.stderr.write('open file failed, %s' % e)
else:
self._fh.seek(0, 2) for r in self._fh.readlines():
# sys.stdout.write(r)
process_line(r) def process_IN_MODIFY(self, event):
path = self._path if path not in os.path.join(event.path, event.name):
return if not self._fh.closed:
for r in self._fh.readlines():
# sys.stdout.write(r)
process_line(r) def process_IN_MOVE_SELF(self, event):
path = self._path if path in os.path.join(event.path, event.name):
sys.stderr.write('monitor file move') def process_IN_ATTRIB(self, event):
pass class Tailer(object): def __init__(self, filename):
super(Tailer, self).__init__()
self._path = filename
self._notifier = None self._init() def __del__(self):
self._notifier.stop() def _init(self):
path = self._path index = path.rfind('/')
wm = pyinotify.WatchManager()
wm.add_watch(path[:index], DIRMASK) handler = Handler(path)
self._notifier = pyinotify.Notifier(wm, handler) def run(self):
self.read_last_10240_word()
while True:
self._notifier.process_events() if self._notifier.check_events():
self._notifier.read_events() def read_last_10240_word(self):
with open(self._path,'rb') as f:
f.seek(-10240,2)
for l in f.readlines():
# print(l.decode())
process_line(l.decode()) def process_line(line_str):
pass
#matcher = re.search(r'\d{4}-\d{2}-\d{2}.*?- (DEBUG|INFO|WARNING|ERROR|CRITICAL) -[\s\S]*?(File ".*?.py", line \d*)', line_str)
matcher = re.search(r'^\d{4}-\d{2}-\d{2}.*?(DEBUG|INFO|WARNING|ERROR|CRITICAL)', line_str)
if not matcher:
print(line_str)
else:
log_level_str = matcher.group(1)
if log_level_str == 'DEBUG':
print('\033[0;32m%s\033[0m' % line_str)
elif log_level_str == 'INFO':
print('\033[0;96m%s\033[0m' % line_str)
elif log_level_str == 'WARNING':
print('\033[0;33m%s\033[0m' % line_str)
elif log_level_str == 'ERROR':
print('\033[0;35m%s\033[0m' % line_str)
elif log_level_str == 'CRITICAL':
print('\033[0;31m%s\033[0m' % line_str) if __name__ == '__main__':
if len(sys.argv[1:]) != 1:
print('Usage: python tail.py </path/to/filename>')
sys.exit(0) path = sys.argv[1]
Tailer(path).run()

使用pyinotify实现加强版的linux tail -f 命令,并且对日志类型的文本进行单独优化着色显示。的更多相关文章

  1. windows下使用tail -f 命令查看实时日志

    经常在linux后台进行日志分析的同学对tail -f 这个命令肯定不陌生了,监控实时系统日志简直不要太方便.但是作为一个自动化测试工程师,我们的代码实际上在本地跑就够了,不需要部署,但是window ...

  2. tail -f 实时跟踪一个日志文件的输出内容

    tail -f  实时跟踪一个日志文件的输出内容 http://hittyt.iteye.com/blog/1927026 https://blog.csdn.net/mengxianhua/arti ...

  3. linux tail -f messages查看控制台失败

    [root@localhost log]# tail -f /var/log/messages ......................... tail: cannot watch `/var/l ...

  4. linux tail -f 和 tail -F的区别 && tail 的断点续传

    bash-1中启动如下进程while [ "true" ] ; do date >> test.log; sleep 1 ; done; bash-2中,tail -f ...

  5. linux之tail -F命令异常file truncated

    使用tail -F收集日志时,经常报出file truncated, 导致日志又重新读取.tail: `test.out' has appeared;  following end of new fi ...

  6. tail -f 命令暂停方法

    Linux 下查看日志时,使用 tail -f 可以不断的刷新日志信息. 例如: tail -f logs.log 此时要想暂停刷新,使用ctrl+s暂停终端.若想继续终端,使用ctrl+q. 若想退 ...

  7. Linux下f命令配置

    一.工具 f 的配置 使用 ========== ========== ========== ========== ========== ==========  ==== 一.配置方法: 首先在lin ...

  8. 关于linux的一点好奇心(四):tail -f文件跟踪实现

    关于文件跟踪,我们有很多的实际场景,比如查看某个系统日志的输出,当有变化时立即体现,以便进行问题排查:比如查看文件结尾的内容是啥,总之是刚需了. 1. 自己实现的文件跟踪 我们平时做功能开发时,也会遇 ...

  9. linux tail 命令详解

    linux ---tail命令 linux中tail命令---用于查看文件内容 最基本的是cat.more和less. 1. 如果你只想看文件的前5行,可以使用head命令,如: head -5 /e ...

随机推荐

  1. [uboot]uboot中显示logo

    http://blog.chinaunix.net/uid-20543672-id-3246292.html

  2. Android——监听事件总结

    各种监听事件 1.按钮 Button(1)点击监听 btn_1.setOnClickListener(new View.OnClickListener() { (2)长按监听 btn_1.setOnL ...

  3. oracle快速创建可用用户

    执行语句 create user utaptest identified by utaptest; create tablespace utaptestspace datafile 'd:\data. ...

  4. android开发(45) 自定义软键盘(输入法)

    概述 在项目开发中遇到一个需求,”只要数字键盘的输入,仅仅有大写字母的输入,某些输入法总是会提示更新,弹出广告等“,使得我们需要自定义输入. 关联到的知识 KeyboardView      一个视图 ...

  5. Spring Cloud Config 配置刷新

    客户端进行刷新操作. 1.添加 actuator包,这样 /refresh url才处于可用状态. <dependency> <groupId>org.springframew ...

  6. java将doc文件转换为pdf文件的三种方法

    http://feifei.im/archives/93 —————————————————————————————————————————————— 项目要用到doc转pdf的功能,一番google ...

  7. PHP zhuaq

    change_html_img_src.php <?php $url=$_GET['url']; $id=$_GET['id']; $type=$_GET['type']; $redis_key ...

  8. jquery学习心得:一个很好的css和js函数调用的例子

    统一目录下的资源结构图: <html><head> <link rel="stylesheet" href="gallery.css&quo ...

  9. Qt中QString::toStdString().c_str() 偶尔存在问题

    假设 QString str = "string"; const char* c = str.toStdString().c_str()单步调试显示的结果可能会是'\0' 而当我这 ...

  10. 百度搜索_如何打开Intellij IDEA的代码提示功能?

    Intellij IDEA是一款优秀的编程软件,相比较Eclipse之下它的用户群较小,但并不代表它的功能就比Eclipse差,如果用顺手了还是特别好用的.代码提示功能对于程序员来说非常重要,那么我们 ...