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

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

最佳答案

如果您使用的是基于类的 View :

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

关于python - 如何在Django的一个HTML页面中打开两个日志文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14888843/

10-13 02:15
查看更多