python实现web分页日志查看

    当咱们维护一个网站时,不管前台仍是后台,常常会出现各类个样的问题。有时候问题很难直观的发现,这个时候只能查看各类日志来跟踪问题。可是查看日志有各类个样的问题。首先,要用各类工具登录到服务器,这个有时候很麻烦。登陆上去可能没有合适的工具查看日志,就算有,中文偶尔也会来个乱码啥的。最郁闷的是有的日志文件很大,打开要等好久,看起来也不方便。html

    基于上面的缘由,我用python的bottle模块作了个web版的分页日志查看器,bottle怎么安装使用具体可看下面的指南:
          http://bottlepy.org/docs/dev/tutorial.htmlpython

    这里没有太多考虑安全因素,若是考虑安全最好加个简单的登陆功能,或者直接对请求ip进行校验。性能方面还须要优化,文件太大仍是有点慢。
    下面是实现代码,只有一个文件:
    web

 1 #coding=utf-8
 2 '''
 3 日志文件查看器
 4 Created on 2013年8月20日
 5 
 6 @author: alala
 7 '''
 8 
 9 import os
10 import bottle
11 from bottle import route, run, template
12 
13 #将自定义模板目录添加到模板搜索路径集合
14 templatesDir = os.getcwd()
15 bottle.TEMPLATE_PATH.insert(0,templatesDir)
16 
17 #日志根目录
18 LOG_DIR = "/Tem/"
19 #每页显示日志行数
20 PAGE_SIZE = 4000
21 
22 #列出某个子目录的全部日志文件
23 @route('/')
24 @route('/<dirName>')
25 def listDir(dirName='logs'):
26     if dirName == 'favicon.ico':
27         return 0
28     #读取目录
29     files = os.listdir(LOG_DIR + dirName)
30     return template('logList', files=files,dirName=dirName)
31 
32 #查看某个日志文件
33 @route('/<dirName>/<logFile>')
34 @route('/<dirName>/<logFile>/<pageNo>')
35 def viewLog(dirName,logFile,pageNo=-1):
36     filePath = LOG_DIR + dirName + "/" + logFile;
37     pageNo = int(pageNo)
38     
39     #获取日志行数
40     lineCount = 0
41     f = open(filePath, 'rb')
42     try:
43         while True:
44             buf = f.read(1024*1024)
45             if not buf:
46                 break
47             lineCount += buf.count('\n')
48     finally:
49         f.close()
50     #计算页数
51     pageCount = lineCount / PAGE_SIZE
52     if lineCount % PAGE_SIZE != 0:
53         pageCount += 1
54     #调整当前页码    
55     print (pageNo, pageCount, pageNo >= pageCount)
56     if (pageNo < 0) or (pageNo >= pageCount) or (pageNo == -1):
57         pageNo = pageCount - 1
58     
59     #读取当页日志
60     lines = []
61     f = open(filePath, 'r')    
62     try:
63         maxNo = (pageNo + 1) * PAGE_SIZE
64         minNo = pageNo * PAGE_SIZE
65         lineNo = 0
66         for line in f:
67             if lineNo >= maxNo:
68                 break
69             elif lineNo >= minNo:
70                 lines.append(line)
71             lineNo += 1
72     finally:
73         f.close()
74     #使用模板构建显示页面    
75     return template('logView', dirName = dirName, logFile = logFile,
76                     pageNo = pageNo,lines = lines, pageCount = pageCount)
77 
78 run(host='localhost', port=5200)
79 #paste提供多线程请求处理,性能比默认的好
80 #run(host='localhost', port=5200,server='paste')

    下面是使用到的两个模板:
    安全

%for f in files:
<a href="{{'/%s/%s' % (dirName, f)}}">{{f}}</a><br/>
%end
logList.tpl
%for i in range(0,pageCount):
    <a href="{{'/%s/%s/%s' % (dirName, logFile, i)}}" 
        style="color:{{'red' if pageNo == i else 'black'}};">{{i}}</a>
%end
<br/>
<br/>
%for line in lines:
{{line}}<br/>
%end
logView.tpl
相关文章
相关标签/搜索