问题描述
我正在研究一个具有以下结构的小型python项目-
I'm working on a small python project that has the following structure -
project
-- logs
-- project
__init.py__
classA.py
classB.py
utils.py
-- main.py
我已经在项目下的 __ init.py __
中设置了日志记录配置如下所示:
I've set up the logging configuration in __init.py__
under project as follows:
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
中的已记录语句不会出现在日志文件中,而两个类中的所有日志语句 classA
和 classB
以及 utils.py
会按预期路由到控制台和日志文件。
Setting up things this way seems to set up the root logger at the package level, and not at the entire project level. As a result, logged statements inside main.py
don't appear in the log file, whereas all log statements in the two classes classA
and classB
as well as utils.py
are routed to the console and the log file as expected.
如何设置日志记录,以便能够对其进行一次配置并在整个项目中使用它?我尝试将日志记录配置语句移至main.py,但似乎没有用。
How do I set up the logging so that I'm able to configure it once and use it across the project? I tried moving the logging configuration statements to main.py, but it didn't seem to work.
def setupLogging():
# Create the Logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
..etc..
def main():
setupLogging()
if __name__ == "__main__":
main()
推荐答案
为整个项目配置一次日志记录是正确的,就像您第一次尝试的那样,而不是每个软件包都单独配置。
It is correct to configure logging only once for the whole project, as you first tried, not each package separately.
您做错的是您将记录器配置为仅当前模块:
What you did wrong is you configured the logger for the current module only:
logger = logging.getLogger(__name__)
相反,您要配置根记录器:
Instead of that, you want to configure the root logger:
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
# ...
root_logger.addHandler(logger_handler)
root_logger.addHandler(console_handler)
为根记录器完成的配置a
The configuration done for the root logger applies to every logger which does not explicitly override it.
然后,您应该在实际记录日志时使用特定的记录器:
Then you should use the specific logger when actually logging:
logger = logging.getLogger(__name__)
logger.warning("I am warning you about %s", something)
这篇关于Python日志记录-多个模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!