如何使用日志记录每个脚本的记录(Python)

时间:2020-03-22 23:34:50

标签: python logging

我遇到一个问题,当前我使用两个日志记录,每个脚本都有自己的日志记录。我什至在第二个脚本中使用了filename="Test1/Logs/hello.txt和Test2,所以文件名是分开的。我的问题是,每当我运行脚本时,该脚本仅保存到一个文件夹,在我的情况下是Test1。即使我运行了应该保存到Test2文件夹日志的test2.py脚本,它也永远不会登录到Test2文件夹中。

我所做的是:


# -------------------------------------------------------------------------
# CLASS A
# -------------------------------------------------------------------------
logging.basicConfig(
    filename='{}{}.txt'.format(/Test1/Logs, datetime.now().strftime("%a %d %B %Y %H_%M_%S")),
    filemode='a',
    level=logging.INFO,
    format='[%(asctime)s]:%(levelname)s:%(funcName)s - %(message)s',
    datefmt=datetime.now().strftime("%H:%M:%S.%f")[:-3]
)

loggingError = logging.getLogger()
logging.warning("Starting: {}".format(datetime.now().strftime("%a %d-%B-%Y %H:%M:%S")))


class A:

    def __init__(self):
        self.logging = loggingError


    def aW1wb3J0RmlsZXM(self):
        self.logging.error(sys.exc_info(), exc_info=True)

# -------------------------------------------------------------------------
# CLASS B
# -------------------------------------------------------------------------
logging.basicConfig(
    filename='{}{}.txt'.format(/Test2/Logs, datetime.now().strftime("%a %d %B %Y %H_%M_%S")),
    filemode='a',
    level=logging.INFO,
    format='[%(asctime)s]:%(levelname)s:%(funcName)s - %(message)s',
    datefmt=datetime.now().strftime("%H:%M:%S.%f")[:-3]
)

loggingError = logging.getLogger()
logging.warning("Starting: {}".format(datetime.now().strftime("%a %d-%B-%Y %H:%M:%S")))


class B:

    def __init__(self):
        self.logging = loggingError


    def aW1wb3J0RmlsZXM(self):
        self.logging.error(sys.exc_info(), exc_info=True)
import A
import B

def main():

        if True:
            B.main()
            break

        if False:
            A.main()
            break


if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(e)

您可以看到,日志记录之间的唯一区别是文件夹名称 filename ,但是即使我运行Class B,它仍然保存到Class A文件夹中。是什么原因呢?

已更新为每个脚本:

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler('{}{}.txt'.format(logsPath, datetime.now().strftime("%a %d %B %Y %H_%M_%S")))
formatter = logging.Formatter('[%(asctime)s]:%(levelname)s:%(funcName)s - %(message)s', "%d-%m-%Y %H:%M:%S")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.warning("Starting: {}".format(datetime.now().strftime("%a %d-%B-%Y %H:%M:%S")))

1 个答案:

答案 0 :(得分:1)

之所以发生这种情况,是因为当您import A运行文件中的所有代码时。特别是对basicConfig的调用。此功能的工作方式是仅在尚未配置日志记录时才起作用,否则不执行任何操作。因此,当您第一次配置import A日志记录时,第二次调用B中的basicConfig不会产生任何作用。

这在官方python文档here中有很好的记录。

编辑: 通过在每个文件中执行类似的操作,可以更容易地完成每个模块的文件记录:

import logging
local_logger = logging.getLogger(__name__)
local_logger.addHandler(logging.FileHandler('filename.log', 'a'))
local_logger.setLevel(logging.INFO)