Python日志记录-多个模块

theguyoverthere

我正在研究一个具有以下结构的小型python项目-

project 
 -- logs
 -- project
    __init.py__
    classA.py
    classB.py
    utils.py
 -- main.py

__init.py__在项目下设置了日志记录配置,如下所示:

import logging
from logging import StreamHandler
from logging.handlers import RotatingFileHandler

# Create the Logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# Create the Handler for logging data to a file
logger_handler = RotatingFileHandler('logs\\mylog.log', maxBytes=1024, backupCount=5)
logger_handler.setLevel(logging.INFO)

#Create the Handler for logging data to console.
console_handler = StreamHandler()
console_handler.setLevel(logging.INFO)

# Create a Formatter for formatting the log messages
logger_formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')

# Add the Formatter to the Handler
logger_handler.setFormatter(logger_formatter)
console_handler.setFormatter(logger_formatter)

# Add the Handler to the Logger
logger.addHandler(logger_handler)
logger.addHandler(console_handler)

用这种方式设置东西似乎是在包级别而不是整个项目级别设置根记录器。其结果是,记录的语句中main.py不会出现在日志文件中,而在两个班的所有日志报表classAclassB以及utils.py被路由到控制台和日志文件的预期。

如何设置日志记录,以便能够对其进行一次配置并在整个项目中使用它?我尝试将日志记录配置语句移动到main.py,但似乎没有用。

def setupLogging():
    # Create the Logger
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)
    ..etc..

def main():   
    setupLogging()

if __name__ == "__main__":
    main()
戒指

像您第一次尝试的那样,对整个项目只配置一次日志记录是正确的,而不是分别对每个软件包进行配置。

您做错的是您只为当前模块配置了记录器:

logger = logging.getLogger(__name__)

取而代之的是,您要配置根记录器:

root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)

# ...

root_logger.addHandler(logger_handler)
root_logger.addHandler(console_handler)

为根记录器完成的配置适用于未明确覆盖它的每个记录器。

然后,您应该在实际记录时使用特定的记录器:

logger = logging.getLogger(__name__)

logger.warning("I am warning you about %s", something)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

多个模块的Python日志记录

如何从多个模块进行日志记录python日志记录

使用多个模块的python日志记录并写入文件和RotatingFileHandler

Python:日志记录模块-全局

python:安装日志记录模块

Python日志记录模块加密

如何使用跨多个模块的日志记录对象来完成Python日志记录?

Python记录StreamHandler不会从模块记录日志

Python日志记录创建多个日志

Python日志记录-禁用导入模块的日志记录

使用Python中的日志记录模块进行颜色日志记录

Python日志记录-dictConfig-子模块的日志记录目标

在Python日志记录中跨多个模块访问记录器

Python日志记录-具有root记录器的多个模块中的配置文件

Python日志记录模块无故返回错误

如何调试python日志记录模块?

Python的日志记录模块线程安全吗?

不同脚本共享的模块的Python日志记录

如何从Python日志记录模块写入Kafka?

python日志记录模块默认在哪里写日志?

使用Python日志记录模块时重复的日志输出

使用Python日志记录模块时重复的日志输出

Airflow + python日志记录模块未写入日志文件

Python日志记录模块未写入日志文件

在 python 日志记录模块中强制日志轮换

即使设置了级别,Python日志记录模块也不记录信息

Python日志记录:使用日志记录模块将数据记录到服务器

Python 日志记录:文件处理程序不记录子模块日志记录调用

如何使用 click_log 控制具有多个模块的 python 项目中的日志记录级别?