python - 如何在 Django 的一个 HTML 页面中打开两个日志文件?

标签 python linux django django-class-based-views

我的 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/

相关文章:

python - 多处理 AttributeError 模块对象没有属性 '__path__'

python - tf.data : "mixing" batch sizes?

我可以在用户空间中遍历进程的页表吗?

c - 在 Linux 内核函数中的缓冲区中查找子字符串

django - PWA 无法使用 Service Worker 与 Django 一起正常工作

python - 多种 ModelManager 过滤方法

python - 由于超时,pipenv 安装失败

c - 循环中的getline()在嵌入式Linux中不断消耗更多内存

python - 获取易趣 OAuth token

Django 模型 __unicode__ 在记录时引发异常