2

と呼ばれるdjangoルートディレクトリに2つのログファイルがapache.error.logありdjango.logます。私のapp/staticフォルダには HTML ファイルがありますmylog.html。ここで、その HTML ページ内のログ ファイルを表示したいと考えています。

これは可能ですか?両方のファイルの最後の 20 行を表示したい。基本的には のようなものですtail -fが、ブラウザ内にあるため、デバッグ用に 1 つのタブを常に開いておくことができます。

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 に答える