6 Star 22 Fork 13

请叫我code哥/ruyangmao

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
tail_log.py 1.61 KB
一键复制 编辑 原始数据 按行查看 历史
请叫我code哥 提交于 2019-10-15 10:24 . 加入实时日志
# -*- encoding=utf8 -*-
__author__ = "code哥"
import sys
import os
import time
from conn_pool import get_redis, REDIS_APP_RUN_LOG
rs = get_redis()
class Tail(object):
def __init__(self, tailed_file):
self.check_file_validity(tailed_file)
self.tailed_file = tailed_file
self.callback = sys.stdout.write
self.register_callback(print_log)
self.follow(s=1)
def follow(self, s=1):
with open(self.tailed_file) as file_:
# Go to the end of file
file_.seek(0, 2)
while True:
curr_position = file_.tell()
line = file_.readline()
if not line:
file_.seek(curr_position)
time.sleep(s)
else:
self.callback(line)
def register_callback(self, func):
self.callback = func
def check_file_validity(self, file_):
if not os.access(file_, os.F_OK):
raise TailError("File '%s' does not exist" % (file_))
if not os.access(file_, os.R_OK):
raise TailError("File '%s' not readable" % (file_))
if os.path.isdir(file_):
raise TailError("File '%s' is a directory" % (file_))
class TailError(Exception):
def __init__(self, msg):
self.message = msg
def __str__(self):
return self.message
def print_log(msg):
rs.rpush(REDIS_APP_RUN_LOG, msg)
# 保存最新500条
rs.ltrim(REDIS_APP_RUN_LOG, 0, 500 - 1)
def main():
Tail('{path}/run.log'.format(path=os.path.dirname(os.path.abspath(__file__))))
if __name__ == '__main__':
main()
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/337317439/ruyangmao.git
git@gitee.com:337317439/ruyangmao.git
337317439
ruyangmao
ruyangmao
wifi

搜索帮助