【问题标题】:can't get python logging using apache2 CustomLog to work properly无法使用 apache2 CustomLog 获取 python 日志记录以正常工作
【发布时间】:2011-07-04 08:56:03
【问题描述】:

我正在尝试使用 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 中集中记录请求的任何其他建议也会有所帮助。

【问题讨论】:

  • 忘了说:我使用的是 Python 2.6.6 和 Apache/2.2.16 (Debian)

标签: python django apache logging apache2


【解决方案1】:

只关注邮件的最后一行。您可能不想为每个请求都运行 python 脚本。您正在折腾约 20MB 的程序来读取单行文本。

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

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

【讨论】:

  • 我的理解是apache启动时进程被apache打开,而apache停止时写入一个eof。所以python只启动一次,apache将所有日志写入它的stdin。不是每行都执行 Python。
  • @Rolf:嗯,好吧,这让我感觉好多了。在那种情况下,我希望你能够做到这一点。当你循环为 readline() 做了什么问题?
  • readline() 每次都返回空字符串。考虑到 apache 在没有要写入的日志行时不断写入 EOF,这种行为似乎是正确的。
【解决方案2】:

我已经开始工作了。 Apache 在停止时关闭标准输入,因此您可以等到 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)

【讨论】:

    猜你喜欢
    • 2014-10-31
    • 2021-08-08
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 2014-09-18
    相关资源
    最近更新 更多