Reputation: 379
I have my two log files in my django root dir called apache.error.log
and django.log
. In my app/static
folder I have the HTML file mylog.html
. Now I want to view those log files inside that HTML page.
Is this possible? I want to view the last 20 lines of both files. basically something like tail -f
, but inside the browser so that I can have my one tab always open for debugging.
Upvotes: 2
Views: 377
Reputation: 10312
If you're using Class Based Views:
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
Upvotes: 3
Reputation: 6052
Create a new view in Django
in the controller, import os
use lastLines = os.popen("tail /path/to/logFile").read()
show these listLines
in the view
Upvotes: 0