【问题标题】:Python Logging - How do I disable a package's Logging?Python 日志记录 - 如何禁用包的日志记录?
【发布时间】:2019-12-03 03:01:54
【问题描述】:

我被这个问题逼疯了。我只想使用我的 basicConfig 进行日志记录,但模块 (uvicorn) 也在记录到文件中。

例子:

2019-11-27 14:44:29,595 - uvicorn - INFO - ('127.0.0.1', 62211) - "GET /consumption/xyz HTTP/1.1" 200

('127.0.0.1', 62211) - "GET /consumption/xyz HTTP/1.1" 200

我不希望出现第二条消息,因为它是重复的...如何禁用它?

更新: 使用的代码...

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logging.getLogger("snowflake.connector.network").disabled = True # remove snowflake network logging
logging.getLogger("snowflake.connector.connection").disabled = True
logging.getLogger('snowflake.connector').setLevel(logging.INFO)
logging.getLogger('boto3').setLevel(logging.INFO)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
logging.getLogger('urllib3').setLevel(logging.CRITICAL)
logging.basicConfig(filename=f'{CFG.get("log_path")}',
                    filemode='w',
                    level=logging.DEBUG,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
                    )
rotating = RotatingFileHandler(f'{CFG.get("log_path")}', maxBytes=1024*1024*500, backupCount=4)
logging.getLogger('').addHandler(rotating)

设置 access-log = False 后的日志。我打了几次 API:

2019-12-02 10:16:26,635 - uvicorn - WARNING - auto-reload only works when app is passed as an import string.
2019-12-02 10:16:26,656 - uvicorn - INFO - Started server process [20653]
2019-12-02 10:16:26,656 - uvicorn - INFO - Waiting for application startup.
2019-12-02 10:16:26,657 - uvicorn - INFO - Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
2019-12-02 10:16:43,379 - uvicorn - INFO - Shutting down
2019-12-02 10:16:43,479 - uvicorn - INFO - Waiting for application shutdown.
2019-12-02 10:16:43,479 - uvicorn - INFO - Finished server process [20653]
Finished server process [20653]

access_log = True 时记录:

2019-12-02 10:17:44,438 - uvicorn - WARNING - auto-reload only works when app is passed as an import string.
2019-12-02 10:17:44,459 - uvicorn - INFO - Started server process [20791]
2019-12-02 10:17:44,459 - uvicorn - INFO - Waiting for application startup.
2019-12-02 10:17:44,460 - uvicorn - INFO - Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
2019-12-02 10:17:58,571 - uvicorn - INFO - ('127.0.0.1', 55861) - "GET / HTTP/1.1" 200
('127.0.0.1', 55861) - "GET / HTTP/1.1" 200

【问题讨论】:

  • 你读过这个吗? uvicorn.org/settings/#logging点--no-access-log
  • 我正在使用 uvicorn.run(),找不到要传入的 arg
  • 这是官网的一段话“如果你以编程方式运行 using,使用 uvicorn.run(...),然后使用等效的关键字参数,例如 uvicorn.run(”示例:应用“,端口=5000,重新加载=真,访问日志=假)”
  • 很糟糕,但是,禁用它会完全禁用该消息。我只需要删除重复的。
  • 等等,但第一行是您的自定义日志?..

标签: python logging starlette uvicorn


【解决方案1】:

logging.basicConfig 添加Handler。然后你去添加另一个。两者都指向同一个文件。

logging.basicConfig(filename=f'{CFG.get("log_path")}',
                    filemode='w',
                    level=logging.DEBUG,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
                    )
rotating = RotatingFileHandler(f'{CFG.get("log_path")}', maxBytes=1024*1024*500, backupCount=4)
logging.getLogger('').addHandler(rotating)

所以要了解如何解决这个问题,最好看看 logging.basicConfig 实际做了什么:

def basicConfig(**kwargs):

    _acquireLock()
    try:
        if len(root.handlers) == 0:
            filename = kwargs.get("filename")
            if filename:
                mode = kwargs.get("filemode", 'a')
                hdlr = FileHandler(filename, mode)
            else:
                stream = kwargs.get("stream")
                hdlr = StreamHandler(stream)
            fs = kwargs.get("format", BASIC_FORMAT)
            dfs = kwargs.get("datefmt", None)
            fmt = Formatter(fs, dfs)
            hdlr.setFormatter(fmt)
            root.addHandler(hdlr)
            level = kwargs.get("level")
            if level is not None:
                root.setLevel(level)
    finally:
        _releaseLock()

内联 basicConfig 导致:

root = logging.getLogger('')
if len(root.handlers) == 0:
    filename = f'{CFG.get("log_path")}'
    mode = 'w'
    hdlr = FileHandler(filename, mode)
    fs = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    dfs = None
    fmt = Formatter(fs, dfs)
    hdlr.setFormatter(fmt)
    root.addHandler(hdlr)
    root.setLevel(logging.DEBUG)

rotating = RotatingFileHandler(f'{CFG.get("log_path")}', maxBytes=1024*1024*500, backupCount=4)
root.addHandler(rotating)

你能看到问题吗?同一个文件用Handler 设置了两次,所以要解决这个问题,把它写成:

root = logging.getLogger('')
if len(root.handlers) == 0:
    filename = f'{CFG.get("log_path")}'
    hdlr = RotatingFileHandler(filename, maxBytes=1024*1024*500, backupCount=4)
    fs = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    fmt = Formatter(fs)
    hdlr.setFormatter(fmt)
    root.addHandler(hdlr)
    root.setLevel(logging.DEBUG)

【讨论】:

  • 您先生是个绅士。感谢您深入解释代码。我现在明白我使用的记录器对象只需要一个处理程序而不是多个处理程序。我不知道 basicConfig 中添加的处理程序,因此感谢您对其进行调查。
  • 谢谢你:)。我原以为我可能选择了一个与原因无关的问题。有时拥有多个处理程序很有用,因为每个处理程序都可以有自己的格式、级别和过滤器。但不是当两者都去同一个文件时。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
  • 2014-07-16
  • 2011-07-16
  • 2018-12-24
  • 2020-01-17
  • 2016-07-04
  • 2018-07-17
相关资源
最近更新 更多