2

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.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
user2024264
  • 349
  • 1
  • 5
  • 12
  • You would have to write a view to read lines from these files and show them in a template. – Rohan Feb 15 '13 at 05:36

2 Answers2

3

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
Matt
  • 8,758
  • 4
  • 35
  • 64
0

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

Pheonix
  • 6,049
  • 6
  • 30
  • 48