Python日志写入终端和日志文件

2024-06-25 23:13:53 发布

您现在位置:Python中文网/ 问答频道 /正文

{cd2>有两个文件。在functions.py中,我有logger设置和一组函数(由下面的一个组成):

class ecosystem():
    def __init__(self, environment, mode):
        self.logger = logging.getLogger(__name__)
            if os.path.exists('log.log'):
                os.remove('log.log')

            handler= logging.FileHandler('log.log')
            if mode.lower()== 'info':
                handler.setLevel(logging.INFO)
                self.logger.setLevel(logging.INFO)
            elif mode.lower()== 'warning':
                handler.setLevel(logging.WARNING)
                self.logger.setLevel(logging.WARNING)
            elif mode.lower()== 'error':
                handler.setLevel(logging.ERROR)
                self.logger.setLevel(logging.ERROR)
            elif mode.lower()== 'critical':
                handler.setLevel(logging.CRITICAL)
                self.logger.setLevel(logging.CRITICAL)
            else:
                handler.setLevel(logging.DEBUG)
                self.logger.setLevel(logging.DEBUG)

            #Logging file format
            formatter = logging.Formatter('    %(levelname)s | %(asctime)s | %(message)s \n')
            handler.setFormatter(formatter)
            #Add the handler to the logger
            self.logger.addHandler(handler)

            self.logger.info('Logging starts here')

    def my_function():
        self.logger.debug('test log'))
        return True

我试图从script.py调用ecosystem.my_function,但当我这么做时,logger.debug消息会同时出现在终端窗口和log.log。你知道为什么会这样吗?在

如果有帮助的话,我还将其他模块导入functions.py,如果这些模块也导入日志,这会导致问题吗?在


Tags: pyselflogifosmodeloggingdef
1条回答
网友
1楼 · 发布于 2024-06-25 23:13:53

看起来您正在使用log.log文件在ecosystem类的__init__方法中初始化记录器。这意味着任何创建ecosystem对象的代码都将初始化记录器。在代码的某个地方,在其中一个文件中,您正在创建该对象,因此记录器被初始化并写入该文件。在

请注意,您不需要自己调用__init__,因为它是在创建对象时调用的。在这通电话之后

my_obj = ecosystem()

将写入日志文件。在

你的文件和新的文件为什么都被你用了。这是因为propagate属性。默认情况下,propagate为True,这意味着您的日志将冒泡在logger的层次结构中,每个日志都将继续处理它。因为默认的根记录器位于层次结构的顶部,所以它也会处理您的日志。将propagate设置为False修复此问题:

^{pr2}$

您可能需要阅读一下logging。另外,如果您想保持日志记录的正常性,check how you can use dict to configure logging。在

相关问题 更多 >