1 Star 0 Fork 13

wudoo/ruyangmao

forked from 请叫我code哥/ruyangmao 
Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
This repository doesn't specify license. Please pay attention to the specific project description and its upstream code dependency when using it.
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/wudoo/ruyangmao.git
git@gitee.com:wudoo/ruyangmao.git
wudoo
ruyangmao
ruyangmao
master

Search