使用python

时间:2017-11-12 04:30:59

标签: python logging

我希望将变量增加1或运行一个函数,在我的情况下每次记录到log - lognum时都会执行此操作。

lognum = 1
logger = logging.getLogger('module')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter(f'----CHUNK {lognum}----\nLEVEL: %(levelname)s\nNAME:%(name)s\nMESSAGE:%(message)s\n----CHUNK {lognum}----\n'))
logger.addHandler(handler)

我无法在setFormatter之后添加代码 - 它只是设置格式化程序。我已经阅读docs进行日志记录,找不到任何内容。

1 个答案:

答案 0 :(得分:1)

您可以使用filters或py3 setLogRecordFactory& getLogRecordFactory将上下文信息添加到日志中。

这是一个快速而又肮脏的例子:

import sys
import logging

logger = logging.getLogger(__name__)
COUNT = 1
FMT = """----CHUNK %(lognum)s----
LEVEL: %(levelname)s
NAME:%(name)s
MESSAGE:%(message)s
----CHUNK %(lognum)s----"""

def main():
    logger.info('hello, world')
    logger.warning('this is a warning log')
    logger.error('this is bad!')

def init_logger():
    log = logging.getLogger(__name__)
    log.setLevel(logging.INFO)
    handler = logging.StreamHandler(stream=sys.stdout)
    formatter = logging.Formatter(fmt=FMT)
    handler.setFormatter(formatter)
    log.addHandler(handler)

    old_factory = logging.getLogRecordFactory()

    def record_factory(*args, **kwargs):
        global COUNT
        record = old_factory(*args, **kwargs)
        record.lognum = COUNT
        COUNT += 1
        return record

    logging.setLogRecordFactory(record_factory)


if __name__ == '__main__':
    init_logger()
    main()

和输出:

----CHUNK 1----
LEVEL: INFO
NAME:__main__
MESSAGE:hello, world
----CHUNK 1----
----CHUNK 2----
LEVEL: WARNING
NAME:__main__
MESSAGE:this is a warning log
----CHUNK 2----
----CHUNK 3----
LEVEL: ERROR
NAME:__main__
MESSAGE:this is bad!
----CHUNK 3----

here you can find使用filters的类似示例。