6 Star 22 Fork 14

请叫我code哥/ruyangmao

Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
Clone or Download
tail_log.py 1.61 KB
Copy Edit Raw Blame History
请叫我code哥 authored 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

Search