如何在Python中更改第三方库的日志级别或将所有日志静音?

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

How to Change the Loglevel or Silence All Logs for a Third Party Library in Python?

问题

以下是您要求的代码部分的翻译:

这是我的代码的外观

#!/usr/bin/env python3
# encoding:utf-8
import logging, asyncua 
logging.basicConfig(format='%(asctime)s | %(levelname)s: %(message)s',
                    level=logging.INFO)

...# 其他内容
logging.info(msg='我的消息')

但似乎asyncua库内部有一个非常冗长的日志设置,即使在info级别也是如此。因此,当我将我的日志级别设置为info或debug时,该库会在控制台中填充不必要的(至少对我来说是不必要的)消息,导致我的自定义日志消息丢失。我正在使用的解决方法是将自己的日志级别设置为ERROR,以抑制其info/debug日志,并将所有我的消息记录为错误,这似乎是一种可怕的解决方法,以避免这种情况。

那么,如何完全消除来自我的导入的任何日志,或将它们都设置为error/warning级别,以确保我的自定义日志不会在控制台中丢失?是否有一种方法可以覆盖所有相关库,不仅仅是asyncua,还包括例如tensorflow

英文:

Here is how my code looks like.

#!/usr/bin/env python3
# encoding:utf-8
import logging, asyncua 
logging.basicConfig(format='%(asctime)s | %(levelname)s: %(message)s',
                    level=logging.INFO)

...# Other stuffs
logging.info(msg='My message')

But seems like the asyncua library has an extremely verbose log setting inside, even at info level. So as I set my loglevel to info or debug, the library itself fills my console with unnecessary (at least to me) messages where my own log messages get lost. The workaround I am using is setting my own loglevel as ERROR to suppress their info/debug log and logging all my messages as error, which seem like a terrible hack to avoid.

So how do I totally silence any log from my imports, or set them all at error/warning level, to make sure my own logs do not get lost in the console? Is there a method that covers all relevant libraries, not just asyncua, but also, for example, tensorflow?

答案1

得分: 1

查找第三方库的文档或源代码,找出顶级日志记录器的名称(例如可能是asyncuatensorflow),然后根据需要设置这些记录器的级别,例如:

logging.getLogger('asyncua').setLevel(logging.ERROR)

使用级别logging.CRITICAL + 1来完全禁止它们的日志输出(假设它们只使用标准的日志级别)。

英文:

Find out the names of the top-level loggers for your third-party libraries from their documentation or source code (e.g. might be asyncua, tensorflow) and then set the level of those loggers to suit your need, e.g.

logging.getLogger('asyncua').setLevel(logging.ERROR)

and use level logging.CRITICAL + 1 to completely silence them (assuming they just use the standard logging levels).

huangapple
  • 本文由 发表于 2023年2月24日 12:00:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552504.html
匿名

发表评论

匿名网友

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

确定