使用apache2 CustomLog无法正常运行python日志记录

时间:2011-02-25 14:58:08

标签: python django apache logging apache2

我正在尝试使用apache的CustomLog指令将日志行传递给python脚本(应该登录到django后端)。我在虚拟主机中使用以下自定义日志行:

CustomLog "|/usr/bin/python -u /home/rolf/feedmemore/myproject/logger.py > /tmp/out.txt 2> /tmp/err.txt" combined

这是logger.py中的主循环:

c = sys.stdin.read(1)
line = ""
while True:

    if c:
        line += c
        if ord(c) == 4:
            break
    else:
        sys.stderr.write("huh?\n")

    if c == '\n':
        print line
        logline(line.rstrip('\n'))
        line = ""

    c = sys.stdin.read(1)

起初我的信念是,如果我从带有read(1)的apache收到“”,那么该程序应该退出。但是,无论服务器活动如何,apache都会继续抛出“”。 /tmp/err.txt快速填满了“嗯?”的。怎么了?

我的日志记录程序在输入完成后应该知道怎么知道并且应该退出?我已经尝试检查0x4(EOT),但这不起作用。

我的第一次尝试是使用“readline()”但是同样失败了。

关于如何在django中集中记录请求的任何其他建议也会有所帮助。

2 个答案:

答案 0 :(得分:0)

只关注你最后一行的信息。您可能不希望为每个请求运行python脚本。你正在投入一个大约20MB的程序来阅读一行文字。

阅读现代系统日志,例如syslog-ng。你为一件非常简单的事情付出了太多的代价。

http://www.balabit.com/sites/default/files/documents/syslog-ng-admin-guide_en.html/configuring_destinations_tcpudp.html

答案 1 :(得分:0)

我已经开始工作了。 Apache在停止时关闭stdin,这样你就可以等到主循环中sys.stdin.closed为True并忽略空字符串。

奇怪的是,apache现在会产生一个额外的僵尸记录器进程。由于僵尸的ppid是1,如果它发现自己的ppid为1,则代码才会退出。

这对我有用:

if os.getppid() == 1:
    sys.exit()
c = sys.stdin.read(1)
line = ""
while not sys.stdin.closed:
    if c:
        line += c

    if c == '\n':
        print line,
        logline(line.rstrip('\n'))
        line = ""

    c = sys.stdin.read(1)
相关问题