python - 如何格式化扭曲的日志?

标签 python logging twisted

使用框架 Twisted,当您使用 startLogging() 时,您会得到如下日志行:

Y-M-D H-m-s [类 - IP] 消息

如何格式化该输出以消除日期和 IP?

谢谢

最佳答案

我现在正在努力解决类似的问题。 “扭曲日志”在 Google 上的第一个结果是 the pretty helpful official documentation on logging ,这让我找到了 application page其中有一个自定义应用程序日志记录行为的示例:

from twisted.application.service import Application
from twisted.python.log import ILogObserver, FileLogObserver
from twisted.python.logfile import DailyLogFile

application = Application("myapp")
logfile = DailyLogFile("my.log", "/tmp")
application.setComponent(ILogObserver, FileLogObserver(logfile).emit)

我猜我可以做到这一点,并使用 FileLogObserver 的自定义子类。我去查看了/usr/lib/python2.6/dist-packages/twisted/python/log.py 中的代码

在这里

class FileLogObserver:
    """
    Log observer that writes to a file-like object.

    @type timeFormat: C{str} or C{NoneType}
    @ivar timeFormat: If not C{None}, the format string passed to strftime().
    """
    timeFormat = None

    def __init__(self, f):
        self.write = f.write
        self.flush = f.flush

    def getTimezoneOffset(self, when):
        """
        Return the current local timezone offset from UTC.

        @type when: C{int}
        @param when: POSIX (ie, UTC) timestamp for which to find the offset.

        @rtype: C{int}
        @return: The number of seconds offset from UTC.  West is positive,
        east is negative.
        """
        offset = datetime.utcfromtimestamp(when) - datetime.fromtimestamp(when)
        return offset.days * (60 * 60 * 24) + offset.seconds

    def formatTime(self, when):
        """
        Format the given UTC value as a string representing that time in the
        local timezone.

        By default it's formatted as a ISO8601-like string (ISO8601 date and
        ISO8601 time separated by a space). It can be customized using the
        C{timeFormat} attribute, which will be used as input for the underlying
        C{time.strftime} call.

        @type when: C{int}
        @param when: POSIX (ie, UTC) timestamp for which to find the offset.

        @rtype: C{str}
        """
        if self.timeFormat is not None:
            return time.strftime(self.timeFormat, time.localtime(when))

        tzOffset = -self.getTimezoneOffset(when)
        when = datetime.utcfromtimestamp(when + tzOffset)
        tzHour = abs(int(tzOffset / 60 / 60))
        tzMin = abs(int(tzOffset / 60 % 60))
        if tzOffset < 0:
            tzSign = '-'
        else:
            tzSign = '+'
        return '%d-%02d-%02d %02d:%02d:%02d%s%02d%02d' % (
            when.year, when.month, when.day,
            when.hour, when.minute, when.second,
            tzSign, tzHour, tzMin)

    def emit(self, eventDict):
        text = textFromEventDict(eventDict)
        if text is None:
            return

        timeStr = self.formatTime(eventDict['time'])
        fmtDict = {'system': eventDict['system'], 'text': text.replace("\n", "\n\t")}
        msgStr = _safeFormat("[%(system)s] %(text)s\n", fmtDict)

        util.untilConcludes(self.write, timeStr + " " + msgStr)
        util.untilConcludes(self.flush)  # Hoorj!

    def start(self):
        """
        Start observing log events.
        """
        addObserver(self.emit)

    def stop(self):
        """
        Stop observing log events.
        """
        removeObserver(self.emit)

我知道这不是解决方案,但这是我到目前为止所学到的。如果我发现任何其他问题,我会发布。

关于python - 如何格式化扭曲的日志?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3700955/

相关文章:

python - 参数是 URL 或路径

python - Python日志记录:左对齐括号

python - Python 的 Twisted Reactor 是如何工作的?

python - 如何在列表 python 中查找并只保留 double ?

python - 在 pypy 翻译期间指定安装的 native 库路径

python - 在 Pandas 中查找前一个交易日非常慢

swift - 从 Framework 内部记录消息到 XCode 控制台

.net - 设计Azure云日志框架

python - 如何从协议(protocol)外部发送 Autobahn/Twisted WAMP 消息?

python - Twisted + SQLAlchemy 和最好的方法