debugging 无法从加载属性,ini到自定义记录器

ngynwnxp  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(315)

我有一个名为CustomLogger的类,它是BaseLogger的子类,BaseLoggerlogging.Logger的子类。BaseLoggerlogger.ini文件加载属性。所以,CustomLogger只是BaseLogger的一个外观。
下面是我的代码:

logger.ini

[loggers]
keys=root

[handlers]
keys=consoleHandler,fileHandler

[formatters]
keys=fileFormatter, consoleFormatter

[logger_root]
level=INFO
handlers=consoleHandler, fileHandler

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

[handler_fileHandler]
class=FileHandler
level=INFO
formatter=fileFormatter
args=('app.log',)

[formatter_fileFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S

[formatter_consoleFormatter]
format=%(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S

base_logger。py

from os import path
import logging
import logging.config

class BaseLogger(logging.Logger):
    def __init__(self, name):
        super().__init__(name)
        config_file_path = path.join(path.dirname(__file__), 'logger.ini')
        logging.config.fileConfig(config_file_path)
        print("Loaded config level:", self.getEffectiveLevel())

custom_logger。py

from .base_logger import BaseLogger

class CustomLogger(BaseLogger):
    def __init__(self, name):
        super().__init__(name)

main.py

from custom_logger import CustomLogger

logger = CustomLogger('root')
logger.info("hello") #doesn't work

它看起来还可以,但是当我在代码中使用CustomLogger时,它似乎没有从ini文件. getEffectiveLevel()返回0,这表示在示例化时未设置记录器级别。
我试过使用logging.setLoggerClass,但也没有工作。

wbgh16ku

wbgh16ku1#

要使用您的配置文件,您可以这样做:

import logging.config

logging.config.fileConfig('logger.ini')
root_logger = logging.getLogger('root')
root_logger.info('test')

更新:

# file: custom_logger.py
import logging.config
from custom_logger_second_file import log_message

logging.config.fileConfig('logger.ini')
root_logger = logging.getLogger('root')
root_logger.info('test')
log_message('message from second file')
# file: custom_logger_second_file.py
import logging.config

def log_message(message):
    root_logger = logging.getLogger('root')
    root_logger.info(message)

相关问题