python-3.x 从2个根记录器记录到1个文件

enyaitl3  于 2022-11-26  发布在  Python
关注(0)|答案(1)|浏览(164)

我有一个快速设置记录器的功能:

def init_logger(name: str, log_path: str):
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)

    cli_handler = logging.StreamHandler()
    cli_handler.setFormatter(CLILoggerFormatter())
    cli_handler.setLevel(logging.INFO)
    logger.addHandler(cli_handler)

    file_handler = logging.handlers.TimedRotatingFileHandler(filename=log_path, when="midnight", encoding="utf-8")
    file_handler.setFormatter(FileLoggerFormatter())
    file_handler.setLevel(logging.DEBUG)
    logger.addHandler(file_handler)

另外,我的python包my_lib包含以下代码行:

logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())

这是main.py文件

import my_lib
import logging

init_logger(__name__, "logs/log.log")
logger = logging.getLogger(__name__)
init_logger("my_lib", "logs/log.log")

根据设计,python包my_libmain.py文件中的所有日志都应该写入到一个文件log.log中(该文件每午夜更改一次)。

--- Logging error ---
Traceback (most recent call last):
  File "C:\Program Files\Python310\lib\logging\handlers.py", line 74, in emit
    self.doRollover()
  File "C:\Program Files\Python310\lib\logging\handlers.py", line 435, in doRollover
    self.rotate(self.baseFilename, dfn)
  File "C:\Program Files\Python310\lib\logging\handlers.py", line 115, in rotate
    os.rename(source, dest)
PermissionError: [WinError 32] The process cannot access the file because it is occupied by another process: 'C:\\Users\\Woopertail\\Desktop\\Test\\logs\\log.log' -> 'C:\\Users\\Woopertail\\Desktop\\Test\\logs\\log.log.2022-11-23'

据我所知,发生这种情况是因为2个根日志程序试图一个接一个地创建和打开一个文件,第二个得到这样的错误。
有没有办法让2个根记录器将记录保存到1个文件中?

bejyjqdl

bejyjqdl1#

如果有人有类似的问题,这里有一个解决方案,帮助我。
我没有向每个logger对象添加处理程序,而是使用了logging.config.dictConfig

import logging
import logging.config

CONFIG = {
    "version": 1,
    "handlers": {
        "file_handler": {
            "class": "logging.handlers.TimedRotatingFileHandler",
            "level": "DEBUG",
            "formatter": "file_formatter",
            "filename": "logs/log.log",
            "when": "midnight",
            "encoding": "utf-8"
        },

        "cli_handler": {
            "class": "logging.StreamHandler",
            "level": "INFO",
            "formatter": "cli_formatter"
        }
    },

    "formatters": {
        "file_formatter": {
            "()": "MyFormatters.FileLoggerFormatter"
        },

        "cli_formatter": {
            "()": "MyFormatters.CLILoggerFormatter"
        }
    },

    "loggers": {
        "main": {
            "handlers": ["file_handler", "cli_handler"],
            "level": "DEBUG"
        },
        "my_lib": {
            "handlers": ["file_handler", "cli_handler"],
            "level": "DEBUG"
        }
    }
}

logging.config.dictConfig(CONFIG)
logger = logging.getLogger("main")

相关问题