英文:
Best way to use a single logger in my python project, overwrite root logger or replace import everywhere?
问题
Title is a bit vague but I think my code examples make it clear. I want to start using a custom logger in a large project of mine.
Currently, in every file that I use logging, I import logging and use that like this:
# file A
import logging
logging.info(...)
I do this in many files. I want to use my own specific logger:
# __init__.py
logger = logging.getLogger('my_logger!')
There are two approaches I think to using this logger everywhere in my project:
Option 1:
Importing the logger defined above in all of my files instead of the logging module:
# file A
from ... import logger
logger.info(...)
Option 2: Overriding the root logger, so that I do not have to replace anything
# __init_
logger = logging.getLogger('my_logger!')
logging.root = logger
Now I do not have to replace the imports in all my files. What is the best option and why?
英文:
Title is a bit vague but I think my code examples make it clear. I want to start using a custom logger in a large project of mine.
Currently, in every file that I use logging, I import logging and use that like this:
# file A
import logging
logging.info(...)
I do this in many files. I want to use my own specific logger:
# __init__.py
logger = logging.getLogger('my_logger!')
There are two approaches I think to using this logger everywhere in my project:
Option 1:
Importing the logger defined above in all of my files instead of the logging module:
# file A
from ... import logger
logger.info(...)
Option 2: Overriding the root logger, so that I do not have to replace anything
# __init_
logger = logging.getLogger('my_logger!')
logging.root = logger
Now I do not have to replace the imports in all my files. What is the best option and why?
答案1
得分: 1
getLogger('foo') 总是返回相同的 Logger 实例,无论在哪里调用它。 (Loggers 有它们自己的全局 "namespace",由模块本身管理。)
无论你想在哪里使用 my_logger,只需使用
import logging
logger = logging.getLogger('my_logger')
应用程序 的工作是确保在启动时正确配置名为 my_logger 的记录器。
英文:
getLogger('foo') always returns the same Logger instance, no matter where it is called. (Loggers have their own global "namespace" managed by the module itself.)
Wherever you want to use my_logger, just use
import logging
logger = logging.getLogger('my_logger')
It's the job of the application to ensure that the logger named my_logger is configured correctly on startup.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论