通过Django中的Ajax输出日志文件 [英] Output log file through Ajax in Django

查看:43
本文介绍了通过Django中的Ajax输出日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于如何从

I have followed an SO's accepted answer on how to read the log file in Django from /var/log/gateway from here and I managed to output the file on terminal like here.

2013-05-09T11:15:02.539091+08:00 localhost gateway[5205]: System starting up...
2013-05-09T12:57:44.160246+08:00 localhost gateway[5205]: System start complete.
2013-05-09T15:13:47.428553+08:00 localhost gateway[4777]: * Unable to connect to device /home/smartsensor1. Device may be offline. *

下一步是,我想输出日志文件并以html显示,我对原始代码做了一些修改,就像这样.

The next step is, I want to output the log file and display it in html, I did it with slight modification from the original code like this.

def Logs(request):
    with open('../../../../../var/log/gateway') as f:
        while True:
            line = f.readline()
            if line:
                print line
                return HttpResponse(line)

因此,在客户端,我根据另一个SO接受的答案,像这样放置Ajax,此处.

So on the client side, I put Ajax like this, based on another SO's accepted answer here.

$.ajax({
    type: "GET", 
    url : "{% url WebServiceApp.logging.Logs %}",
    success: function (data) {
            $("#output").append(data);
            setTimeout("doUpdate()", 2000);
    }
});
}

setTimeout("doUpdate()", 2000);

这样,Ajax的输出数据将继续显示日志文件的第一行.在这种情况下,是这样的

With this, the output data from Ajax kept on displaying the first line of the log file. Where in this case, is like this

2013-05-09T11:15:02.539091+08:00 localhost gateway[5205]: System starting up...
2013-05-09T11:15:02.539091+08:00 localhost gateway[5205]: System starting up...
2013-05-09T11:15:02.539091+08:00 localhost gateway[5205]: System starting up...

我知道发生这种情况是因为每次ajax进入服务器时,服务器都会做它需要做的事情,然后将输出(它是日志文件的第一行)发回并通过HttpResponse输出并完成了循环,但从未成功有机会再做一条线,因为它已经完成了.完成另一个查询后,它会一次又一次地执行相同的操作.

I know this occur because everytime ajax went to the server, the server does what it needs to do and send back the output which is the first line of the log file and output through the HttpResponse and completed the cycle and it never got a chance to do another line because it is completed already. When another query is done, it does the same thing again, and again.

因此,可能的解决方案是客户端一次询问服务器,并且服务器保持逐行输出日志文件并将其发送给客户端.我不确定这是否可行,所以我在这里问任何专家如何实现结果,以便我可以逐行输出日志文件/

So the possible solution is client ask the server one time, and the server keep output the log file line by line and send it out to client. I am not sure if this is even possible, so here I am asking any expert on how to possibly achieve the result where I can output the log file line by line/

推荐答案

我已经找到解决此问题的方法,方法是执行服务器发送的事件

I've found a way to solve this is by doing the Server-Sent Event

在服务器端,我使用 django-sse ,它依赖于

On server side, I use django-sse that is dependent on sse

import os
from django.conf import settings
from django.views.generic import View
from django_sse.views import BaseSseView
import time
from django.utils.timezone import now
from datetime import datetime
from django.utils.timezone import now
from dateutil import parser

class MySseEvents(BaseSseView):
    def iterator(self):
        while True:
            if not os.path.exists('/var/log/gateway'):
                file('/var/log/gateway', 'w+').close()
            with open('/var/log/gateway') as f:
                while True:
                    #get the current time
                    currenttime = now()
                    #read a line from gateway
                    line = f.readline()
                    if line:
                        #split the line read into 4 section
                        str = line.split(' ',3)
                        #compare if the time from the log file is less than the current time
                        logtime = parser.parse(str[0])
                        if logtime >= currenttime:
                            #print when the log is written after the current time
                            output = '%s: %s' % (datetime.strftime(logtime,'%d/%m %H:%M %p'), str[3])
                            self.sse.add_message("line", output)
                            time.sleep(1)
                            yield

if logtime> = currenttime:上面的检查是为了确保html仅在页面加载后打印出日志,而不是整个日志文件.

The if logtime >= currenttime: check that I did above is to make sure that html only print out the logs after the time the page is loaded not the whole log file.

然后,在HTML5方面,我所做的操作类似于作者在我提供的第一个链接上显示的示例.

Then on the HTML5 side I did similar to what the example made by the author shown on the first link that I have provided.

<div id="tab9" class="tab_content">
    <table>
        <tr>
            <td>
                <p> Shows the records of the logs on gateway.</p>
                <div style="border:1px solid; height: 200px; width: 850px; overflow: auto;" id="output"></div>
            </td>
        </tr>
    </table>
</div>
<script>
$(document).ready(function() {
    var source = new EventSource('/gtwy/logging/');
    var events_dom = $("#output");

    source.addEventListener("line", function(e) {
        events_dom.append(e.data + "<br>");
    });
});
</script>

使用此方法,我设法显示了可用的日志.我面临的唯一问题是创建需要权限的网关文件本身,因为我正在尝试在/var/log 中创建它.

Using this, I managed to display the log as it is available. The only problem that I face is to create the gateway file itself that it needs permission because I'm trying to create it in /var/log.

这篇关于通过Django中的Ajax输出日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆