【问题标题】:Can a wrapper/decorator function in Python disable all logging inside the code it wrapsPython中的包装器/装饰器功能可以禁用它包装的代码中的所有日志记录吗
【发布时间】:2022-10-23 07:10:05
【问题描述】:

我想装饰/包装一个函数并防止记录该函数范围内的所有日志。

def prevent_logs_wrapper(func):
    ...
    ...
    ...

@prevent_logs_wrapper
def some_logs():
    logger.info('Log an info msg')
    logger.warning('Log a warning msg')

而不是这个输出

[INFO] Log an info msg
[WARNING] Log an warning msg

我们不会得到任何日志。

【问题讨论】:

  • 是的。您可以设置logger.setLevel(logging.FATAL),然后在功能存在时恢复级别。但是,并不是说记录器通常在不同的线程之间共享,所以如果您的应用程序依赖于线程,这将不起作用。
  • 我的代码使用线程,所以我不能完全阻止日志记录。我正在研究根据包装器调用的堆栈过滤日志。阻止包装器调用的所有内容。有一个日志功能“findCaller”可能会起作用。

标签: python logging python-decorators


【解决方案1】:

在日志记录中没有这种可能性,但它在 Polog 库中可用。安装它:

$ pip install polog

并将unlog decorator 用于您的功能:

from polog import log, unlog

@unlog
def function():
    log("some text") # It won't work!

Polog 比标准日志更强大,尝试使用它。

【讨论】:

    猜你喜欢
    • 2017-04-10
    • 2014-02-26
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 2021-05-20
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多