Python 如何在Django中在一个HTML页面中打开两个日志文件?
我在django根目录中有两个日志文件,分别是Python 如何在Django中在一个HTML页面中打开两个日志文件?,python,linux,django,django-class-based-views,Python,Linux,Django,Django Class Based Views,我在django根目录中有两个日志文件,分别是apache.error.log和django.log。在我的app/static文件夹中,我有一个HTML文件mylog.HTML。现在我想查看HTML页面中的日志文件 这可能吗?我想查看两个文件的最后20行。基本上类似于tail-f,但在浏览器内部,这样我就可以始终打开我的一个选项卡进行调试。在Django中创建一个新视图 在控制器中,导入操作系统 使用lastLines=os.popen(“tail/path/to/logFile”).read
apache.error.log
和django.log
。在我的app/static
文件夹中,我有一个HTML文件mylog.HTML
。现在我想查看HTML页面中的日志文件
这可能吗?我想查看两个文件的最后20行。基本上类似于
tail-f
,但在浏览器内部,这样我就可以始终打开我的一个选项卡进行调试。在Django中创建一个新视图
在控制器中,导入操作系统
使用lastLines=os.popen(“tail/path/to/logFile”).read()
如果使用基于类的视图,请在视图中显示这些
列表行
:
class LogTemplateView(TemplateView):
template_name = "mylog.html"
apache_log_file = "apache.error.log"
django_log_file = "django.log"
def get_context_data(self, **kwargs):
"""
This has been overriden to give the template access to the log files.
i.e. {{ apache_log_file }} and {{ django_log_file }}
"""
context = super(LogTemplateView, self).get_context_data(**kwargs)
context["apache_log_file"] = self.tail(open(self.apache_log_file, "r"), 20)
context["django_log_file"] = self.tail(open(self.django_log_file, "r"), 20)
return context
# Credit: Armin Ronacher - http://stackoverflow.com/a/692616/1428653
def tail(f, n, offset=None):
"""Reads a n lines from f with an offset of offset lines. The return
value is a tuple in the form ``(lines, has_more)`` where `has_more` is
an indicator that is `True` if there are more lines in the file.
"""
avg_line_length = 74
to_read = n + (offset or 0)
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None], \
len(lines) > to_read or pos > 0
avg_line_length *= 1.3
您必须编写一个视图来读取这些文件中的行并在模板中显示它们。