Python记录多个模块,每个模块记录到单独的文件

时间:2020-03-07 03:10:31

标签: python logging module

我有一个主脚本和多个模块。现在,我有了日志记录设置,所有模块的所有日志记录都放入同一个日志文件中。当将它们全部放在一个文件中时,很难调试。因此,我想将每个模块分成自己的日志文件。我还希望看到每个模块使用的请求模块到使用它的模块的日志中。我不知道这是否有可能。我到处搜索并尝试了所有可以想到的方法,但总是返回到将所有内容记录到一个文件中,或者将设置记录到每个模块中,然后从我的主模块中启动脚本,而不是将其导入为模块。

main.py

import logging, logging.handlers
import other_script.py

console_debug = True
log = logging.getLogger()

def setup_logging():    
    filelog = logging.handlers.TimedRotatingFileHandler(path+'logs/api/api.log',
                when='midnight', interval=1, backupCount=3)
    filelog.setLevel(logging.DEBUG)
    fileformatter = logging.Formatter('%(asctime)s %(name)-15s %(levelname)-8s %(message)s')
    filelog.setFormatter(fileformatter)
    log.addHandler(filelog)

    if console_debug:
        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(name)-15s: %(levelname)-8s %(message)s')
        console.setFormatter(formatter)
        log.addHandler(console)

if __name__ == '__main__':
    setup_logging()

other_script.py

import requests
import logging

log = logging.getLogger(__name__)

1 个答案:

答案 0 :(得分:0)

python日志记录的一个非常基本的概念是,日志记录到的每个文件,流或其他位置都等同于一个处理程序。因此,如果您希望每个模块都登录到不同的文件,则必须为每个模块提供自己的处理程序。这也可以从中心位置进行。在您的main.py中,您可以添加此内容以使other_script模块日志记录到单独的文件中:

other_logger = logging.getLogger('other_script')
other_logger.addHandler(logging.FileHandler('other_file'))
other_logger.propagate = False

仅当您向根记录器添加处理程序时,才需要最后一行。如果您将传播保持为默认值True,那么所有日志也将发送到root loggers处理程序。在您的方案中,最好甚至不使用根记录器,而使用像main中的getLogger('__main__')之类的特定命名记录器。

相关问题