Python 日志记录问题:输出中缺少一些日志

Python logging issue: some logs are missing from the output

我正在尝试了解 python 日志记录。我创建了一个具有以下结构的项目。

    .
    ├── config
    │   └── configfile.conf
    ├── mytest
    │   ├── pyvmomi.py
    │   └── s_lib.py
    ├── VM_dep.py
    └── vm_setup.py

VM_dep.py 是主文件:

#! /usr/bin/env python3

import logging
from mytest import pyvmomi
from vm_setup import SetupVM


LOGGER = logging.getLogger(__name__)

TEMP_FOLDER = "."

def main():
    LOGGER.info("Running as user: %s", "John Doe")

    
    pyvmomi.create_vm()
    LOGGER.info("VM deployed successfully, IP address: %s", "10.234.103.222")

    vm_to_setup = SetupVM()
    vm_to_setup.configure_vm()


if __name__ == "__main__":
        main()

Pyvmomi.py 文件:

from pathlib import Path
import logging
import logging.config

basefolder = Path(__file__).parents[1]
configfile = (basefolder / "config/configfile.conf").resolve()
logging.config.fileConfig(configfile)

# create logger
logger = logging.getLogger('pyvmomi_lib')


def create_vm():
        logger.info("Pyvmomi")
    

vm_setup.py 文件

#! /usr/bin/env python3

import logging
# from mytest import s_lib  <-- this line is intentionally commented


LOGGER = logging.getLogger(__name__)


class VMSetupException(Exception):
    """Create custom exception type."""


class SetupVM:
    def configure_vm(self):
        LOGGER.info(
                "===================== Setup VM =================================="
            )

s_lib.py

from pathlib import Path
import logging.config


basefolder = Path(__file__).parents[1]
configfile = (basefolder / "config/configfile.conf").resolve()
# print(configfile)
logging.config.fileConfig(configfile)

# create logger
logger = logging.getLogger("opcc_k8s_lib")

logger.info("Hiya LOG LIBRARY")

我注意到一个我无法理解的行为。 在 vm_setup.py 文件中,我注释了一行:

# from mytest import s_lib

只要注释掉这一行,输出结果如下:

❯ python3 VM_dep.py
12-26-2021 05:29:31 PM __main__ VM_dep INFO Running as user: John Doe 
12-26-2021 05:29:31 PM pyvmomi_lib pyvmomi INFO Pyvmomi
12-26-2021 05:29:31 PM __main__ VM_dep INFO VM deployed successfully, IP address: 10.234.103.222 
12-26-2021 05:29:31 PM vm_setup vm_setup INFO ===================== Setup VM
    ==================================

但是当我取消注释上面的行时,输出变为:

❯ python3 VM_dep.py
12-26-2021 05:33:08 PM opcc_k8s_lib s_lib INFO Hiya LOG LIBRARY
12-26-2021 05:33:08 PM __main__ VM_dep INFO Running as user: John Doe
12-26-2021 05:33:08 PM __main__ VM_dep INFO VM deployed successfully, IP address: 10.234.103.222
12-26-2021 05:33:08 PM vm_setup vm_setup INFO ===================== Setup VM ==================================

我在输出中没有得到 12-26-2021 05:29:31 PM pyvmomi_lib pyvmomi INFO Pyvmomi 这个

当我们在 vm_setup.py 文件中导入 s_lib 时,它会再次运行此 logging.config.fileConfig(configfile)(第一次在 importing pyvmomi lib 时调用它。 我相信再次加载 fileConfig 会导致此问题,但我不明白为什么。 任何帮助将不胜感激。

这是配置文件:

[loggers]
keys=root,simpleConsoleExample

[handlers]
keys=consoleHandler

[formatters]
keys=simpleConsoleFormatter

[logger_root]
level=INFO
handlers=consoleHandler

[logger_simpleConsoleExample]
level=INFO
handlers=consoleHandler
qualname=simpleConsoleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=simpleConsoleFormatter
args=(sys.stdout,)

[formatter_simpleConsoleFormatter]
format=%(asctime)s %(name)s %(module)s %(levelname)s %(message)s
datefmt=%m-%d-%Y %I:%M:%S %p

我通过在 s_lib.py 中添加 ,disable_existing_loggers=False) 来解决您的问题。默认值是true。这里是 a link to Python Doc


from pathlib import Path
import logging.config


basefolder = Path(__file__).parents[1]
configfile = (basefolder / "config/configfile.conf").resolve()
# print(configfile)
logging.config.fileConfig(configfile,disable_existing_loggers=False)

# create logger
logger = logging.getLogger("opcc_k8s_lib")

logger.info("Hiya LOG LIBRARY")

我在笔记本电脑上得到的输出

nabs@LAPTOP:~/Whosebug$ python3 VM_dep.py
12-26-2021 02:28:59 PM opcc_k8s_lib s_lib INFO Hiya LOG LIBRARY
12-26-2021 02:28:59 PM __main__ VM_dep INFO Running as user: John Doe
12-26-2021 02:28:59 PM pyvmomi_lib Pyvmomi INFO Pyvmomi
12-26-2021 02:28:59 PM __main__ VM_dep INFO VM deployed successfully, IP address: 10.234.103.222
12-26-2021 02:28:59 PM vm_setup vm_setup INFO ===================== Setup VM ==================================