向模块添加神奇的全局方法

发布于 2024-09-24 03:52:40 字数 368 浏览 2 评论 0原文

我开始使用 Python 日志记录模块,但除非我希望所有消息都显示“root”,否则我必须为每个模块创建一个记录器,而一遍又一遍地这样做有点痛苦。

我想如果有一个神奇的 __logger__() 方法可以返回当前模块的记录器,并在必要时创建它,那会很方便。一个可以在没有括号的情况下调用的神奇 __logger__ 变量会更好。我该怎么办呢?

例如,在名为 foo 的模块中,我可以调用 __logger__.debug('this is a debug message for the foo module'),它将在我的控制台中显示为:

DEBUG:foo:这是 foo 模块的调试消息

I'm starting to get into the Python logging module, but unless I want all messages to say "root" I have to create a logger for each module, and it's kind of a pain to do that over and over again.

I was thinking it would be handy if there were a magic __logger__() method that would return a logger for the current module, creating it if necessary. A magic __logger__ variable that could be called without parenthesis would be even better. How would I go about that?

For example, in a module named foo, I could call __logger__.debug('this is a debug message for the foo module'), and it would show up in my console as:

DEBUG:foo:this is a debug message for the foo module

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

祁梦 2024-10-01 03:52:40

使用: ,并像这样使用它:

logger = logging.getLogger(__name__)

您可以在班级顶部

logger.warn(...)
logger.log(...)

You can use:

logger = logging.getLogger(__name__)

at the top of your class, and use it like so:

logger.warn(...)
logger.log(...)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文