Best way to use a single logger in my python project, overwrite root logger or replace import everywhere?

huangapple go评论81阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年3月3日 23:06:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75628737.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定