2

我的 django 根目录中有两个日志文件,apache.error.log名为django.log. 在我app/static的文件夹中,我有 HTML 文件mylog.html。现在我想在那个 HTML 页面中查看这些日志文件。

这可能吗?我想查看这两个文件的最后 20 行。基本上类似于tail -f,但在浏览器中,这样我就可以始终打开一个选项卡进行调试。

4

2 回答 2

3

如果您使用基于类的视图:

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
于 2013-02-15T05:49:15.680 回答
0

在 Django 中创建一个新视图

在控制器中,import os

采用lastLines = os.popen("tail /path/to/logFile").read()

listLines在视图中显示这些

于 2013-02-15T05:38:00.047 回答