【问题标题】:Disable Logger for websockets Package in Python在 Python 中禁用 websockets 包的 Logger
【发布时间】:2019-02-16 07:29:19
【问题描述】:

我正在使用websockets包在python中创建一个websocket服务器;同时我在不同的日志级别大量使用logging

websocketsdocumentation 提到了记录器配置,并且可以将其更改为日志级别 ERROR 使用

     logger = logging.getLogger('websockets.server')
     logger.setLevel(logging.ERROR)
     logger.addHandler(logging.StreamHandler())

然而,这对我的代码没有任何影响,无论我放在哪里(在导入下方,websockets 导入之前,__main__ 内)。我想要两种配置——一种是全局日志配置,另一种是 websockets 服务器的记录器配置。

另一种选择是完全禁用 websockets 模块的日志记录,但我不知道该怎么做。有什么想法吗?

【问题讨论】:

    标签: python-3.x logging websocket


    【解决方案1】:

    事实证明,发出大量调试消息的不仅是websockets.server,还有其他消息。我最终通过使用根记录器配置中的 %(name)s 字段来查找这些包,并且可以找到 websockets.protocol 负责附加消息。

    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s %(name)s %(levelname)-8s  %(message)s',
        datefmt='(%H:%M:%S)')
    
    # disable all loggers from different files
    logging.getLogger('asyncio').setLevel(logging.ERROR)
    logging.getLogger('asyncio.coroutines').setLevel(logging.ERROR)
    logging.getLogger('websockets.server').setLevel(logging.ERROR)
    logging.getLogger('websockets.protocol').setLevel(logging.ERROR)
    

    【讨论】:

      【解决方案2】:

      当你启动一个 websocket 时,设置:

      websocket.enableTrace(False) 
      

      不会在控制台中记录或显示任何 DEBUG 和 hart beat 消息。

      我的示例代码:

      def start_websocket(url, listen_method):
      """
      Start a websocket connection.
      
      :param url: string
      :param listen_method: method
      """
      # Enable or Disable logging
      websocket.enableTrace(False)
      
      ws = websocket.WebSocketApp(
          url,
          on_message=listen_method,
          on_error=on_error,
          on_close=on_close
      )
      
      ws.on_open = on_open
      
      ws.run_forever(ping_interval=3, ping_timeout=2)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-02
        • 1970-01-01
        • 2015-08-16
        • 1970-01-01
        相关资源
        最近更新 更多